Is there something like the FileSystemWatcher for Sql Server Tables?

前端 未结 5 444
广开言路
广开言路 2021-01-13 13:36

i would like my windows service (to be written in .NET) to recognize when new rows are added to a specific table, but instead of pulling the data from the sql-server i would

相关标签:
5条回答
  • 2021-01-13 14:22

    The closest you'll get in Sql Server 2005 is a trigger. Sql Server 2008 also has change data capture.

    0 讨论(0)
  • 2021-01-13 14:31

    There's also the ADO.NET SqlDependency mechanism if you're using client side ADO.NET with C# or VB.NET

    A SqlDependency object can be associated with a SqlCommand in order to detect when query results differ from those originally retrieved. You can also assign a delegate to the OnChange event, which will fire when the results change for an associated command. You must associate the SqlDependency with the command before you execute the command. The HasChanges property of the SqlDependency can also be used to determine if the query results have changed since the data was first retrieved.

    You basically associate a SqlDependency with your SqlCommand, and provide an event handler that gets called when values that make up the result set of that SqlDependency change.

    using(SqlCommand cmd = new SqlCommand(queryStatement, _conn))
    { 
       cmd.Notification = null;
    
       SqlDependency dependency = new SqlDependency(cmd);
    
       dependency.OnChange += 
           new OnChangeEventHandler(OnChange);
    
        ......
    }
    

    In the event handler, you can then do whathever you need to do.

    void OnChange(object sender, SqlNotificationEventArgs e)
    {
      SqlDependency dependency = sender as SqlDependency;
    
      (do whatever you need to do - e.g. reload the data)
    
    }
    

    Marc

    0 讨论(0)
  • 2021-01-13 14:37

    Yes, there is.

    http://msdn.microsoft.com/en-us/library/ms171157(SQL.90).aspx

    0 讨论(0)
  • 2021-01-13 14:39

    You could use a trigger with a webservice call from the database. But I have no idea how bad (if any) impact will be against the database.

    0 讨论(0)
  • 2021-01-13 14:42

    Be careful using SqlDependency class to monitor changes in database tables - it has problems with memory leaks. However, you can use your own realization with DDL triggers and SQL Service Broker API or use one of open source projects, e.g. SqlDependencyEx:

    int changesReceived = 0;
    using (SqlDependencyEx sqlDependency = new SqlDependencyEx(
              TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME)) 
    {
        sqlDependency.TableChanged += (o, e) => changesReceived++;
        sqlDependency.Start();
    
        // Make table changes.
        MakeTableInsertDeleteChanges(changesCount);
    
        // Wait a little bit to receive all changes.
        Thread.Sleep(1000);
    }
    
    Assert.AreEqual(changesCount, changesReceived);
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题