SqlDependency.OnChange未在datetime列上使用过滤器触发

时间:2015-08-15 16:26:40

标签: c# sql-server tsql sqldependency query-notifications

我在SqlDependency中使用此SQL语句时遇到问题。它根本不会激活SqlDependency.OnChange事件,但会在SQL Server查询窗口中按预期返回结果。

SELECT [Order].OrderId
FROM [dbo].[Order]
WHERE [Order].CreatedOn > '20150815 21:11:57.502'

我在这里阅读了{strong>支持的SELECT语句部分https://technet.microsoft.com/en-us/library/ms181122(v=sql.105).aspx,但没有发现违反任何规则。

有什么想法吗?

更新

我的完整代码如下:

    private void CheckForNewOrders(DateTime dt)
    {
        string json = null;
        string conStr = ConfigurationManager.ConnectionStrings["connstring"].ConnectionString;

        using (SqlConnection connection = new SqlConnection(conStr))
        {
            string query = string.Format(@"
                    SELECT [Order].OrderId
                    FROM [dbo].[Order]
                    WHERE [Order].CreatedOn > '{0}'"
, dt.ToString("yyyyMMdd HH:mm:ss.fff"));  // 20150814 00:00:00.000

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                command.Notification = null;
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();
                    json = "testing ... "; reader[0].ToString();
                }
            }
        }
    }

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            CheckForNewOrders(DateTime.Now);
        }
    }

更新(回应jmelosegui的回答):

            query = string.Format(@"
                    SELECT [Order].OrderId
                    FROM [dbo].[Order]
                    WHERE [Order].CreatedOn > @CreatedOn");

...

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                command.Parameters.Add("@CreatedOn", SqlDbType.DateTime);
                command.Parameters["@CreatedOn"].Value = DateTime.Now;

                command.Notification = null;
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                ...
                }
            }

1 个答案:

答案 0 :(得分:0)

首先,检查所有sql依赖服务的限制。当sql表更改将触发时,where子句在sql依赖项事件中不起作用。您的查询应该被修改。

query = string.Format(@"
                SELECT [Order].OrderId
                FROM [dbo].[Order]
                ORDER BY [dbo].[Order].DateTime desc
        );

请应用这些更改并调试项目。