2015-01-31 79 views

回答

0

是的,我有解決方案,如果你想使用聚合函數像count(*)來查詢sql依賴。首先在你的倉庫中仍然使用select查詢。但是在讀者中,您只需計算讀者執行命令的數據。這樣

int count = 0; 
command = new SqlCommand(@"select Edolpuz_DB.dbo.TABEL_KONFIRMASI_PEMBAYARAN.ID_BUKTI_PEMBAYARAN from Edolpuz_DB.dbo.TABEL_KONFIRMASI_PEMBAYARAN where Edolpuz_DB.dbo.TABEL_KONFIRMASI_PEMBAYARAN.IS_NEW = @room", connect); 
       command.Parameters.AddWithValue("room", true); 
       try 
       { 
        command.Notification = null; 
        SqlDependency dependency = new SqlDependency(command); 
        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); 
        if (connect.State == ConnectionState.Open) 
         connect.Close(); 
        connect.Open(); 
        reader = command.ExecuteReader(); 
        while (reader.Read()) 
        { 
         count++; 
        } 
        return count; 
       } 
       catch { return 0; } 
       finally { connect.Close(); } 
0

東西要小心使用SqlDependency類 - 它有problems內存泄漏。 Hovewer,你可以使用SqlDependency類的開源實現 - SqlDependencyEx。它使用數據庫觸發器和本機Service Broker通知來接收有關表更改的事件。這是一個使用示例:

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您可以監視插入和刪除,避免UPDATE,它爲您提供了理想的結果:COUNT的行爲。希望這可以幫助。

相關問題