SQL依赖关系不会触发

时间:2012-01-26 20:11:49

标签: c# sql-server-2008 sqldependency

我已经尝试设置SQL依赖项来触发“Count Rows”查询(用C#编写,SQL Server 2008 Express),但在原始订阅SQLNotificationType之后,事件处理程序似乎永远不想再触发(尽管添加了行,我已经检查了SQL并且它返回了预期的值......)。

我的代码如下。任何想法都非常感谢!

编辑:此代码所在的项目是WPF程序。我将这个特定的代码存储在一个单独的类中,我的WPF程序在“Initialized”事件处理程序中创建了一个实例。然后我在这个类中有一个方法,它首先基本上调用ConnectToDatabase(),然后调用SetupSQLDependency()。

编辑2:作为旁注,这个程序是WPF,我希望将其分发给少数用户。目标是每当将新行添加到数据库时,都会使用某些信息更新WPF。我认为这是最好的方法,而不是总是查询数据库。

        private void ConnectToDatabase()
        {
        //This method is the first to be called, and is the entry 
        // point into my SQL database code.

            databaseConnection = new SqlConnection(connectionString);

            // Setup command used in SqlDependecy 
            SqlCommand tempCmd = new SqlCommand();
            tempCmd.Connection = databaseConnection;
            tempCmd.CommandText = "SELECT COUNT(ID) FROM [Example].[dbo].[ExampleTable]";
            sqlCmd = tempCmd;

            try
            { databaseConnection.Open(); }
            catch (Exception e)
            { writeDebug(e.ToString()); }
        }        

        private void SetupSQLDependency()
        {
            SqlDependency.Stop(connectionString);
            SqlDependency.Start(connectionString);

            sqlCmd.Notification = null;

            // create new dependency for SqlCommand
            SqlDependency sqlDep = new SqlDependency(sqlCmd);
            sqlDep.OnChange += new OnChangeEventHandler(sqlDep_OnChange);

            SqlDataReader reader = sqlCmd.ExecuteReader();
        }

        private void sqlDep_OnChange(object sender, SqlNotificationEventArgs e)
        {
            // FROM: http://msdn.microsoft.com/en-us/a52dhwx7.aspx

            if (e.Type == SqlNotificationType.Change)
            {
            //++++++ THIS IS THE BLOCK THAT IS NEVER TRIGGERED ++++++//
                // Have to remove this as it only work's once
                SqlDependency sqlDep = sender as SqlDependency;
                sqlDep.OnChange -= sqlDep_OnChange;

                // Resetup Dependecy
                SetupSQLDependency();
            }
            else if (e.Type == SqlNotificationType.Subscribe)
            {
                double te = 12; // Used this just to test a break... code is useless
            }
        }

1 个答案:

答案 0 :(得分:1)

我认为这里的问题是COUNT。有关详细信息,请参阅MSDN documentation for Supported SELECT Statements

  

除非语句使用GROUP BY表达式,否则SELECT语句中的投影列可能不包含聚合表达式。提供GROUP BY表达式时,选择列表可能包含聚合函数COUNT_BIG()或SUM()。 [...]

相关问题