Using SqlDependency To Monitor SQL Database Changes
Tue ,23/02/2010In this tutorial, I will use the SqlDependency class and Query notifications to monitor SQL Server 2005 database data changes. Query Notifications allow an application to be notified when data has changed in the database.
The purpose of this class is to save you from having to continuously re-query the database to get new data. You would have probably done this by setting up a timer that executes every X amount of seconds so that your display control would be displaying the most up-to-date information. You will no longer have to do this.
We will be using a Service Broker and a QUEUE in SQL Server 2005. These were new additions to SQL Server 2005. I will assume these are also in SQL Server 2008, but can’t guarantee.
My example will be doing something very simple. I have a “Users” table in my database with two fields: FirstName and LastName. I am simply displaying these in a ListBox on one form. On a second form, I have textboxes to insert the data into the database.
So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.
USING [YourDatabaseName] CREATE QUEUE NameChangeQueue; CREATE SERVICE NameChangeService ON QUEUE NameChangeQueue ([http://schemas.microsoft.com/sql/notifications/postquerynotification]); GRANT SUBSCRIBE QUERY NOTIFICATIONS TO YourUserName;
You can now see that we have a new queue and a new service.

Now we move on to the code. The first thing you will need to do is to test if the connecting user has the privileges for the query notifications.
private bool DoesUserHavePermission()
{
try
{
SqlClientPermission clientPermission = new SqlClientPermission(PermissionState.Unrestricted);
// will throw an error if user does not have permissions
clientPermission.Demand();
return true;
}
catch
{
return false;
}
}
Next, we have our method to get the user names from the database.
private void GetNames()
{
if (!DoesUserHavePermission())
return;
lbNames.Items.Clear();
SqlDependency.Stop(connectionString);
SqlDependency.Start(connectionString);
using (SqlConnection cn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT FirstName, LastName FROM dbo.[Users]";
cmd.Notification = null;
SqlDependency dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(dep_OnChange);
cn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
lbNames.Items.Add(dr.GetString(0) + " " + dr.GetString(1));
}
}
}
}
}
THIS IS VERY IMPORTANT.
1. In the previous code, you will notice that my SQL query does not use the “*” wildcard to return all columns. You MUST return the exact columns that you want. If you use the “*”, it will cause you to have unwanted consequences.
2. Also in the previous code, you will notice that my SQL query contains the “two-part” table name. This is also REQUIRED. Using just “TableName” instead of “owner.TableName” will also cause unwanted consequences.
Here is the method for the OnChange event
void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
// this event is run asynchronously so you will need to invoke to run on UI thread.
if (this.InvokeRequired)
lbNames.BeginInvoke(new MethodInvoker(GetNames));
else
GetNames();
// this will remove the event handler since the dependency is only for a single notification
SqlDependency dep = sender as SqlDependency;
dep.OnChange -= new OnChangeEventHandler(dep_OnChange);
}
You will also need to stop the dependency when the form closes so that it doesn’t leave it running.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SqlDependency.Stop(connectionString);
}
The other events…
private void Form1_Load(object sender, EventArgs e)
{
GetNames();
}
private void btnShowForm_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
And my simple second form’s code..
private void btnSave_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection("Data Source=alfordr;Initial Catalog=MyTestDatabase;User Id=dev;Password=dev;"))
{
using (SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Users VALUES (@FirstName, @LastName)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
}
}
And that is really all you have to do. Here are a couple of screenshots.
Before clicking “Save”…

After clicking “Save”…..

As you can see from my code, I am simply inserting data into my database when the Save button is clicked. When the data is inserted, a notification is sent to the application, which is handled by the OnChange event. The OnChange event then invokes the GetNames method which re-queries the database to get the new information. This makes a huge performance improvement because I ONLY query when I need to.
This works for inserts, updates, and deletes.
The purpose of this class is to save you from having to continuously re-query the database to get new data. You would have probably done this by setting up a timer that executes every X amount of seconds so that your display control would be displaying the most up-to-date information. You will no longer have to do this.
We will be using a Service Broker and a QUEUE in SQL Server 2005. These were new additions to SQL Server 2005. I will assume these are also in SQL Server 2008, but can’t guarantee.
My example will be doing something very simple. I have a “Users” table in my database with two fields: FirstName and LastName. I am simply displaying these in a ListBox on one form. On a second form, I have textboxes to insert the data into the database.
So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.In this tutorial, I will use the SqlDependency class and Query notifications to monitor SQL Server 2005 database data changes. Query Notifications allow an application to be notified when data has changed in the database.
The purpose of this class is to save you from having to continuously re-query the database to get new data. You would have probably done this by setting up a timer that executes every X amount of seconds so that your display control would be displaying the most up-to-date information. You will no longer have to do this.
We will be using a Service Broker and a QUEUE in SQL Server 2005. These were new additions to SQL Server 2005. I will assume these are also in SQL Server 2008, but can’t guarantee.
My example will be doing something very simple. I have a “Users” table in my database with two fields: FirstName and LastName. I am simply displaying these in a ListBox on one form. On a second form, I have textboxes to insert the data into the database.
So first, we need to create the Queue and the Service broker and assign the privileges to the SQL user.
