語言
若要在查詢結果變更時收到通知,請使用通知請求設定 SqlCommand。 在自訂伺服器佇列中,或在您不想維護即時相依性物件時,可以使用通知請求。
建立通知請求
建立 SqlNotificationRequest 物件,並在執行前將其指派給指令的 Notification 屬性。 伺服器註冊請求後,你不需要保留請求物件。 查詢隊列中的通知,並依應用程式需求回應。 通知可能在應用程式關閉時抵達,且重新啟動後仍可查看。
執行具有相關聯通知的命令時,原始結果集的任何變更會觸發將訊息傳送至通知要求中設定的 SQL Server 佇列。
輪詢 SQL Server 佇列並解讀訊息的方法取決於您的應用程式。 應用程式負責輪詢佇列,並根據訊息的內容做出回應。
備註
搭配使用 SQL Server 通知要求 SqlDependency 時,請自行命名佇列,而不是使用預設服務名稱。
授予使用者請求通知所需的伺服器權限。 這個 SqlNotificationRequest 類別並未增加用戶端安全要求。
範例
以下片段建立物件 SqlNotificationRequest 並將其與 SqlCommand關聯。 安裝 Microsoft.Data.SqlClient NuGet 套件並匯入 Microsoft.Data.Sql 和 Microsoft.Data.SqlClient。 這個 Options 值指定服務代理服務及其所承載的資料庫,而非佇列本身。 依照 啟用查詢通知 的說明建立服務與佇列。
' 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.
另請參閱
- SQL Server 中的查詢通知
- ADO.NET 概觀