언어

SqlDependency로 변경 내용 감지

쿼리 결과가 원래 검색된 결과와 다른 경우를 감지하려면 명령을 실행하기 전에 SqlCommand 개체를 SqlDependency와 연관시킵니다. 결과가 변경될 때 알림을 받으려면 OnChange 이벤트를 구독합니다. 종속성의 HasChanges 속성을 확인하여 결과가 변경되었는지 여부를 확인할 수도 있습니다.

보안 고려사항

기본 데이터가 변경될 때 알림을 받으려면 Start를 호출합니다. 종속성 인프라는 수신기에 대해 SqlConnection를 엽니다. 데이터베이스 보안 주체에게 필요한 Service Broker 및 쿼리 알림 권한을 부여합니다. 코드 액세스 보안은 최신 .NET에서는 지원되지 않습니다. 자세한 내용은 쿼리 알림 사용 설정을 참조하세요.

예시

다음 단계에서는 종속성을 선언하고, 명령을 실행하고, 결과 집합이 변경될 때 알림을 받는 방법을 보여 줍니다.

  1. 애플리케이션 초기화 시 SqlDependency.Start를 호출하여 클라이언트 수신기를 시작합니다.

  2. 서버에 연결하고 Transact-SQL(T-SQL) 문을 정의할 SqlCommand 및 SqlConnection 개체를 만듭니다.

  3. SqlDependency 개체를 만들거나 다시 사용하고 SqlCommand 개체와 연결합니다. 종속 개체는 필요에 따라 SqlNotificationRequest 개체를 만들고 명령과 연결합니다. 알림 요청에는 종속성에 대한 내부 식별자가 포함됩니다. 생성자는 리스너를 시작하지 않습니다.

  4. OnChange 개체의 SqlDependency 이벤트에 이벤트 처리기를 등록합니다.

  5. 해당 Execute 메서드 중 하나를 사용하여 명령을 실행합니다. 명령에 알림 요청이 포함되어 있으므로 서버는 지정된 큐에 대한 알림용으로 해당 쿼리를 등록합니다.

  6. 애플리케이션 종료 시 동일한 연결 문자열 및 큐 이름을 사용하여 SqlDependency.Stop를 호출합니다.

이후에 사용자가 기본 데이터를 변경하는 경우 Microsoft SQL Server는 이러한 변경 내용에 대해 보류 중 알림이 있음을 감지하고, SqlConnection를 호출하여 생성된 기본 SqlDependency.Start을 통해 처리되어 클라이언트로 전달되는 알림을 게시합니다. 클라이언트 수신기는 무효화 메시지를 수신합니다. 그러면 클라이언트 수신기는 연결된 SqlDependency 개체를 찾아 OnChange 이벤트를 발생시킵니다.

다음 코드 조각은 샘플 애플리케이션의 디자인 패턴을 보여 줍니다. Microsoft.Data.SqlClient NuGet 패키지를 설치하고 C# 또는 Visual Basic에서 Microsoft.Data.SqlClient을 가져옵니다.

이러한 조각은 기존 Service Broker 큐를 사용합니다. queueName을(를) 큐의 정규화되지 않은 이름으로 설정하고 notificationOptions을(를) service=<service-name>;local database=<database-name>로 설정합니다. 알림을 해당 큐로 라우팅하는 서비스를 지정합니다. 동일한 연결 문자열 및 큐 이름을 Start와 Stop에 전달합니다. 자세한 내용은 쿼리 알림 사용을 참조하세요.

Sub Initialization()
    ' Create a dependency connection.
    SqlDependency.Start(connectionString, queueName)
End Sub

Sub SomeMethod()
    ' Assume connection is an open SqlConnection.
    ' Create a new SqlCommand object.
    Using command As New SqlCommand( _
      "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers", _
      connection)

        ' Create a dependency and associate it with the SqlCommand.
        Dim dependency As New SqlDependency(command, notificationOptions, 0)
        ' Maintain the reference in a class member.
        ' Subscribe to the SqlDependency event.
        AddHandler dependency.OnChange, AddressOf OnDependencyChange

        ' Execute the command.
        Using reader = command.ExecuteReader()
            ' Process the DataReader.
        End Using
    End Using
End Sub

' Handler method
Sub OnDependencyChange(ByVal sender As Object, _
    ByVal e As SqlNotificationEventArgs)
    ' Handle the event (for example, invalidate this cache entry).
End Sub

Sub Termination()
    ' Release the dependency
    SqlDependency.Stop(connectionString, queueName)
End Sub
void Initialization()
{
    // Create a dependency connection.
    SqlDependency.Start(connectionString, queueName);
}

void SomeMethod()
{
    // Assume connection is an open SqlConnection.

    // Create a new SqlCommand object.
    using (SqlCommand command=new SqlCommand(
        "SELECT ShipperID, CompanyName, Phone FROM dbo.Shippers",
        connection))
    {

        // Create a dependency and associate it with the SqlCommand.
        SqlDependency dependency=new SqlDependency(command, notificationOptions, 0);
        // Maintain the reference in a class member.

        // Subscribe to the SqlDependency event.
        dependency.OnChange+=new
           OnChangeEventHandler(OnDependencyChange);

        // Execute the command.
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Process the DataReader.
        }
    }
}

// Handler method
void OnDependencyChange(object sender,
   SqlNotificationEventArgs e )
{
  // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    // Release the dependency.
    SqlDependency.Stop(connectionString, queueName);
}

참고 항목