2

「CountRows」クエリ(C#、SQL Server 2008 Expressで記述)で起動するようにSQL依存関係を設定しようとしましたが、元のサブスクリプションSQLNotificationTypeが実行された後、イベントハンドラーは(行にもかかわらず)再度起動したくないようです。追加されており、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
            }
        }
4

1 に答える 1

2

ここでの問題はCOUNTです。詳細については、サポートされているSELECTステートメントのMSDNドキュメントを参照してください。

SELECTステートメントの射影された列には、ステートメントでGROUP BY式を使用しない限り、集計式を含めることはできません。GROUP BY式が指定されている場合、選択リストには集計関数COUNT_BIG()またはSUM()が含まれる場合があります。[...]

于 2012-02-08T21:39:53.437 に答える