SqlCommand の実行と SqlNotificationRequest (ADO.NET)

サーバーからフェッチした後で、データが変更される場合があります。当然、もう一度クエリを実行すると、前回とは異なる結果セットが得られます。SqlCommand を適切に構成することで、このような場合に通知を生成することができます。 この機能は、サーバー上でカスタムの通知キューを使用する場合や、実際のオブジェクトを保持しない場合に役に立ちます。

通知要求の作成

SqlNotificationRequest オブジェクトを使用して通知要求を作成し、それを SqlCommand オブジェクトにバインドできます。 いったん要求が作成されれば、SqlNotificationRequest オブジェクトは不要です。 通知がないかどうかをキューに照会し、適宜、それに応じた処理を行うことができます。 通知は、アプリケーションをシャットダウンしてから再起動した場合でも受けることができます。

コマンドに通知を関連付けて実行した場合、元の結果セットになんらかの変更が生じると、通知要求で構成した SQL Server キューにメッセージが送信されます。

SQL Server のキューをポーリングしメッセージを解釈する方法は、アプリケーションごとに固有なものになります。 メッセージの内容に基づくキューのポーリングや処理は、アプリケーションによって異なります。

メモメモ

SqlDependency によって SQL Server 通知要求を使用する場合は、既定のサービス名を使用せずにキュー名を独自に作成します。

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 notficationRequest As New SqlNotificationRequest()
notficationRequest.id = "NotificationID"
notficationRequest.Service = "mySSBQueue"

' Associate the notification request with the command.
command.Notification = notficationRequest
' 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 notficationRequest=new SqlNotificationRequest();
notficationRequest.id="NotificationID";
notficationRequest.Service="mySSBQueue";

// Associate the notification request with the command.
command.Notification=notficationRequest;
// 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)