SqlDependency example in Ado.Net C#

SqlDependency is Ado.net Notification service just like SqlTableDependency.

In this tutorial, you will learn how to use SqlDependency class to notify c# application when some changes done in database tables. This is basically a notification mechanism, when some data changes happen in database we can add some more action on onChange event, actions like logging, sending email, broadcasting updated rate etc.

sql dependency example in c#

SqlDependency class depend on SqlConnection object, in order to receive notification from SQL Database, the dependency infrastructure depends on SQLClientPermission and Code Access Security and Ado.Net classes like SqlCommand and Connection ect.

Create SQL table in database

create TABLE [dbo].[tbStock](
	[StockId] [bigint]  primary key identity(1,1)  NOT NULL ,
	[quantity] [int] NOT NULL,
	[price] [decimal](18, 2) NOT NULL,
	[productName] [varchar](50) NOT NULL,
	[updatedOn] [datetime] NOT NULL

Insert some data for testing

		   (120,504.05,'LPB',getdate()) ,

Enabling Query Notifications

We need to create a queue like in below example we have created a queue with name "StockChangeMessages"

Then create a notification service on that queue.

CREATE QUEUE StockChangeMessages;  
CREATE SERVICE StockChangeNotifications  
  ON QUEUE StockChangeMessages  

Enable service broker and grant "SUBSCRIBE QUERY NOTIFICATIONS" permission to current login user.

SqlDependency with SqlCommand Object

Now we need to understand how SqlDependency class detect changes made in sql database with the help of Ado.net SqlCommand object.

Create a c# console application and write the following code.

Here are few things you must know before starting with SqlDependency implementation in C# code.

  • When writing any sql statement in sql command object, we should not use any * mark in SQL Statement.

    for example Select * from [dbo].[tbStock]; not right

    select statement should have all column name specified, like Select stockid, quantity, price, productname from [dbo].[tbStock]

  • We must query on base table only, we cannot query on view, cannot use any type of join in the query

  • There should not be calculated column in the query, we also cannot use function like avg, max, min etc.

SqlDependency implementation in C#

Here we write an task to get all stock details from database, then we see when any stock price changes in sql database how SqlDependency onChange events gets fired.

public async Task<List<Stock>> GetStockDetails()
            var stockDetails = new List<Stock>();
            Stock _stock = null;
        using (SqlConnection con = new SqlConnection(Util.DBConnectionString))
            SqlCommand cmd = new SqlCommand("Select stockid, quantity, price, productname from [dbo].[tbStock]", con);
            SqlDependency dependency = new SqlDependency(cmd);
            dependency.OnChange += new OnChangeEventHandler(Dependency_OnChange);
            SqlDataReader reader = await cmd.ExecuteReaderAsync();
            while (await reader.ReadAsync())
                _stock = new Stock();
                _stock.Price = Convert.ToDecimal(reader["price"]);
                _stock.Qty = Convert.ToInt32(reader["quantity"]);
                _stock.Product = Convert.ToString(reader["productName"]);
    catch (Exception ex)
        throw (ex);
    return stockDetails;

Connection string, make sure you have added integrated security=SSPI in your connection string like example below, this is required for SqlDependency object to access database.

public class Util
    public static string DBConnectionString
            return "Server ='com111\\SQLEXPRESS'; Database='MLData'; User ID='sa1'; Password ='pass100';Trusted_Connection=False;MultipleActiveResultSets=true;integrated security=SSPI";
SqlDependency OnChange Event

When any changes happen in database then this event will get executed.

private void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
    if (e.Type == SqlNotificationType.Change)

You may be interested in following examples

SqlDependency Example
Learn MS-SQL Development
Ado.net Interview Questions Answers
Connect SQL database using Ado.Net component from Asp.net application, learn how to use Ado.net as data access layer.
Ado.Net C# Examples | Join Asp.Net MVC Course