要在 SQL 2005+ 中监视对 SQL 表或记录的更改,您可以使用 SqlDependency 类。
它的目标是在 ASP.NET 或中间层服务中使用,其中单个服务器正在管理针对数据库的活动订阅,而不是由数百个客户端管理订阅。根据您所指的客户端的最大数量,您可能希望构建一个缓存池服务,该服务可以管理针对您的客户端的 SQL 通知订阅。
在它内部使用使用服务代理的 SqlNotificationRequest,而不是通知服务。因此,这应该适用于 SQL 2008 等。
SqlDependency 的 MSDN
void Initialization()
{
// Create a dependency connection.
SqlDependency.Start(connectionString, queueName);
}
void SomeMethod()
{
// Assume connection is an open SqlConnection.
// Create a new SqlCommand object.
SqlCommand command=new SqlCommand(
"SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers",
connection);
// Create a dependency and associate it with the SqlCommand.
SqlDependency dependency=new SqlDependency(command);
// Maintain the refence in a class member.
// Subscribe to the SqlDependency event.
dependency.OnChange+=new OnChangeEventHandler(OnDependencyChange);
// Execute the command.
command.ExecuteReader();
// Process the DataReader.
}
// Handler method
void OnDependencyChange(object sender,
SqlNotificationsEventArgs e )
{
// Handle the event (for example, invalidate this cache entry).
}
void Termination()
{
// Release the dependency.
SqlDependency.Stop(connectionString, queueName);
}
“ Using and Monitoring SQL 2005 Query Notifications ” 文章介绍了在代码中设置它的步骤(以 Web 应用程序为例)以及订阅 Service Broker 所需的适当 SQL 权限等。
ASP.NET(Web 缓存)类也可用于 Web 场景。