언어
쿼리 결과가 변경될 때 알림을 받으려면 알림 요청으로 SqlCommand를 구성합니다. 사용자 지정 서버 큐 또는 라이브 종속성 개체를 유지 관리하지 않으려는 경우 알림 요청 기능을 사용합니다.
알림 요청 만들기
실행하기 전에 SqlNotificationRequest 개체를 만들고 명령의 Notification 속성에 할당합니다. 서버가 요청을 등록한 후에는 요청 개체를 유지할 필요가 없습니다. 큐에서 알림을 쿼리하고 애플리케이션에 필요한 대로 응답합니다. 애플리케이션이 종료되는 동안 알림이 도착하여 다시 시작한 후에도 계속 확인할 수 있습니다.
연결된 알림이 있는 명령이 실행되면 원래 결과 집합에 대한 변경 내용이 알림 요청에서 구성된 SQL Server 큐에 메시지를 보내는 트리거입니다.
SQL Server 큐를 폴링하고 메시지를 해석하는 방법은 애플리케이션에 따라 다릅니다. 애플리케이션은 큐를 폴링하고 메시지 내용에 따라 반응합니다.
비고
SQL Server 알림 요청을 SqlDependency사용하는 경우 기본 서비스 이름을 사용하는 대신 고유한 큐 이름을 만듭니다.
사용자에게 알림 요청에 필요한 서버 권한을 부여합니다. 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.