2012-01-26 54 views
1

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

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

编辑:此代码所在的项目是一个WPF程序。我有这个特殊的代码存储在一个单独的类,我的WPF程序创建一个'初始化'事件处理程序的实例。然后我在这个类中有一个方法,它首先调用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 
      } 
     } 
+0

你可以详细说明这个代码的存在方式吗?例如,如果这段代码存在于'Page'中,并且在'OnLoad'事件中被调用,那么你必须记住你的页面类只是在页面被渲染时才活着,然后一个新的类是为每个请求实例化。所以你的事件订阅和'sqlCmd'变量实例不会被保留(并且最终会导致mem泄漏)。 – CodingGorilla

+0

已编辑 – keynesiancross

+0

以上好,出于某种原因我以为你在ASP.NET中这样做。那么你的'SqlNotificationType.Change'只会触发一次,或者根本不会? – CodingGorilla

回答

1

我相信这里的问题是COUNT。请参阅MSDN documentation for Supported SELECT Statements以获取更多信息:

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

+0

之前使用过这些,你是对的 - 我刚才意识到这一点,但忘了更新它。感谢那。我结束了每隔几秒钟重新查询数据库.... – keynesiancross