语言
要在查询结果更改时接收通知,请使用通知请求配置 SqlCommand。 对自定义服务器队列使用通知请求,或者在您不想维护实时依赖项对象时使用通知请求。
创建通知请求
创建 SqlNotificationRequest 对象,并在执行前将其分配给命令的 Notification 属性。 服务器注册请求后,无需保留请求对象。 查询队列以获取通知,并按照应用程序的要求作出响应。 当应用程序关闭时,通知可能会到达,并在重启后保持可用状态。
在对关联通知执行命令时,对原始结果集所做的任何更改都会触发向在通知请求中配置的 SQL Server 队列发送消息。
轮询 SQL Server 队列和解释消息的方式取决于您的应用程序。 应用程序负责轮询队列并根据消息的内容做出响应。
注释
在 SqlDependency 中使用 SQL Server 通知请求时,请创建自己的队列名称,而不是使用默认的服务名称。
向用户授予请求通知所需的服务器权限。 该 SqlNotificationRequest 类不会增加客户端安全要求。
示例:
以下片段创建对象 SqlNotificationRequest 并将其与 SqlCommand 关联。 安装 Microsoft.Data.SqlClient NuGet 包并导入Microsoft.Data.SqlClient和Microsoft.Data.Sql。 值 Options 表示 Service Broker 服务和托管它的数据库,而不是队列本身。 按照 “启用查询通知”中所述创建服务和队列。
' Assume connection is an open SqlConnection.
' Create a new SqlCommand object.
Dim command As New SqlCommand( _
"SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers", connection)
' Create a SqlNotificationRequest object.
Dim notificationRequest As New SqlNotificationRequest()
notificationRequest.UserData = "NotificationID"
notificationRequest.Options = "service=ContactChangeNotifications;local database=AdventureWorks"
' Associate the notification request with the command.
command.Notification = notificationRequest
' Execute the command.
command.ExecuteReader()
' Process the DataReader.
' You can use Transact-SQL syntax to periodically poll the
' SQL Server queue to see if you have a new message.
// 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 SqlNotificationRequest object.
SqlNotificationRequest notificationRequest=new SqlNotificationRequest();
notificationRequest.UserData = "NotificationID";
notificationRequest.Options = "service=ContactChangeNotifications;local database=AdventureWorks";
// Associate the notification request with the command.
command.Notification=notificationRequest;
// Execute the command.
command.ExecuteReader();
// Process the DataReader.
// You can use Transact-SQL syntax to periodically poll the
// SQL Server queue to see if you have a new message.