SQL SQL 中的依赖和数据引用

SQL dependency and data refering in SQL

当我们使用 sql 依赖项时,我们需要始终引用 sql,如下所示 SELECT ActivityDate FROM [bba-reman].MyLog

我只是想知道如果我这样写上面的内容sql那么行得通吗

SELECT TOP 1 ActivityDate FROM [bba-reman].MyLog

SELECT TOP 5 ActivityDate FROM [bba-reman].MyLog

我正在寻求建议和指导。

private void RegisterNotification()
{
    string tmpdata = "";
    System.Data.SqlClient.SqlDependency.Stop(connectionString);
    System.Data.SqlClient.SqlDependency.Start(connectionString);

    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();

            cmd.CommandText = "SELECT ActivityDate FROM [bba-reman].MyLog";
            dep = new SqlDependency(cmd);
            dep.OnChange += new OnChangeEventHandler(OnDataChange);

            SqlDataReader dr = cmd.ExecuteReader();
            {
                while (dr.Read())
                {
                    if (dr[0] != DBNull.Value)
                    {
                        tmpdata = dr[0].ToString();
                    }
                }
            }

            dr.Dispose();
            cmd.Dispose();
        }
    }
    finally
    {
        //SqlDependency.Stop(connStr);
    }
}

根据 SQL 服务器联机丛书 (https://msdn.microsoft.com/en-us/library/t9x04ed2.aspx),使用 QueryNotifications 的限制之一是语句不能使用 TOP 表达式。 SqlDependency 只是 QueryNotifications 的更高级别实现,它负责 Service Broker 管道。

SqlDependency class has a lot of restrictions as well as the memory leak problems. An absence of the TOP instruction is the one of them. Hovewer, you can use an open source realization of the SqlDependency class - SqlDependencyEx。它使用数据库触发器和本机 Service Broker 通知来接收有关 table 更改的事件。这是一个用法示例:

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);

使用 SqlDependecyEx 您可以分别监视 INSERTDELETEUPDATE 并在事件参数中接收实际更改的数据 (xml)目的。过滤传入消息可帮助您实现理想的行为。希望对您有所帮助。