Programmer's Highway

C# Tips and simple code

I'm very sorry for machine translation in English.

C# SQL Server 2005 Query Notification using SqlDependency

Sample code for query notification using SqlDependency.

By registering the event handler and SqlCommand to SqlDependency, database changes are notified.

using System.Data.SqlClient;
    private SqlDependency sqlDependency;
    
    /// <summary>
    /// Query Notification
    /// </summary>
    private void button1_Click(object sender, EventArgs e)
    {
        // Connection Strings
        string connectionString = "Data Source=127.0.0.7;Initial Catalog=TestDatabase;Integrated Security=True;";
    
        // Start SqlDependency.
        SqlDependency.Start(connectionString);
    
        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
        {
            sqlConnection.Open();
            sqlCommand.CommandText = "SELECT Student.Name, Student.Sex, Student. FROM dbo.Student";
        
            // Register the event handler.
            this.sqlDependency = new SqlDependency(sqlCommand);
            this.sqlDependency.OnChange += OnChange;
        
            // If you need a query, call sqlCommand.ExecuteReader()
            sqlCommand.ExecuteNonQuery();
        }
    }
    
    /// <summary>
    /// Query Notification Event
    /// </summary>
    private void OnChange(object sender, EventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("OnChange");
    
        // If you do not need any more delete event
        this.sqlDependency.OnChange -= OnChange;
    }
			

Note

  1. Query notification Supported by only a specific command(Special Considerations Using Query Notifications
  2. Are also notified if other than the SELECT column has been changed. So, If Age exists in the table, such as Name, Sex, in addition to Grade, it is also subject to monitoring
  3. The table name is specified by the schema name. So, The default schema name dbo in the sample so dbo.Student

For more information, please check the page for MSDN Query Notifications in SQL Server

Visual Studio 2010, .NET Framework 4, Microsoft SQL Server 2008