Language
クエリ結果の変更時に通知を受信するには、通知要求を使用して SqlCommand を構成します。 カスタム サーバー キューを使用する場合や、ライブ依存関係オブジェクトを維持しない場合は、通知要求を使用します。
通知要求の作成
SqlNotificationRequest オブジェクトを作成し、実行前にコマンドの Notification プロパティに割り当てます。 サーバーが要求を登録した後、要求オブジェクトを保持する必要はありません。 キューに対して通知のクエリを実行し、アプリケーションの要件に応じて応答します。 通知は、アプリケーションのシャットダウン中に到着し、再起動後も利用可能です。
コマンドに通知を関連付けて実行した場合、元の結果セットになんらかの変更が生じると、通知要求で構成した SQL Server キューにメッセージが送信されます。
SQL Server のキューをポーリングしメッセージを解釈する方法は、アプリケーションごとに固有なものになります。 アプリケーションは、メッセージの内容に基づいてキューのポーリングと応答を行います。
注
SqlDependency と共に SQL Server 通知要求を使用する場合は、既定のサービス名を使用するのではなく、独自のキュー名を作成してください。
通知を要求するために必要なサーバー権限をユーザーに付与します。 SqlNotificationRequest クラスでは、クライアント側のセキュリティ要件は追加されません。
例
次のフラグメントは、 SqlNotificationRequest オブジェクトを作成し、それを SqlCommandに関連付けます。
Microsoft.Data.SqlClient NuGet パッケージをインストールし、Microsoft.Data.SqlとMicrosoft.Data.SqlClientをインポートします。
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.