SqlCommand可以設定為在從伺服器擷取數據變更之後產生通知,如果再次執行查詢,結果集會不同。 這適用於您想要在伺服器上使用自定義通知佇列,或不想維護實時物件的案例。
建立通知請求
您可以使用 SqlNotificationRequest 物件,將通知要求系結至 SqlCommand 物件來建立通知要求。 建立要求之後,您就不再需要 SqlNotificationRequest 物件。 您可以查詢佇列中是否有任何通知,並適當地回應。 即使應用程式已關閉並後續重新啟動,仍可能會發生通知。
執行具有相關聯通知的命令時,原始結果集的任何變更會觸發將訊息傳送至通知要求中設定的 SQL Server 佇列。
輪詢 SQL Server 佇列並解讀訊息的方法取決於您的應用程式。 應用程式負責輪詢佇列,並根據訊息的內容做出回應。
備註
搭配使用 SQL Server 通知要求 SqlDependency 時,請自行命名佇列,而不是使用預設服務名稱。
沒有任何新的用戶端安全元素 SqlNotificationRequest。 這主要是伺服器功能,而且伺服器已建立用戶必須要求通知的特殊許可權。
範例
下列代碼段示範如何建立SqlNotificationRequest並將其與SqlCommand關聯。
' 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.id = "NotificationID"
notificationRequest.Service = "mySSBQueue"
' 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.id="NotificationID";
notificationRequest.Service="mySSBQueue";
// 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 概觀