Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come posso avvisare il mio programma quando il database è stato aggiornato?

Il database di polling non è una soluzione molto elegante.

SqlDependency da ADO.NET sarà utile nel tuo caso. Non utilizza il meccanismo di polling ma di notifica. Le notifiche sono fornite da Service Broker nel tuo database, quindi dovrai abilitare questo servizio nel tuo database. Il OnChange l'evento verrà generato quando la tabella specificata cambia (aggiornamento, eliminazione, inserimento..)

Ecco un esempio di come utilizzare SqlDependency:

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);
        // Maintain the refence 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);
}

da http://msdn.microsoft.com/en-us/library/ 62xk7953.aspx

Ecco come abilitare Service Broker (nota che avrai l'esclusività sul database per farlo - meglio farlo dopo il riavvio del server sql):http://blogs.sftsrc.com/stuart/archive/2007/06/13/42.aspx (Link interrotto)

Possibile collegamento alternativo:http://technet. microsoft.com/en-us/library/ms166086(v=sql.105).aspx