我在 SqlDependency 中使用此 SQL 语句时遇到问题。它根本没有激活 SqlDependency.OnChange 事件,而是在 SQL Server 查询窗口中按预期返回结果。
SELECT [Order].OrderId
FROM [dbo].[Order]
WHERE [Order].CreatedOn > '20150815 21:11:57.502'
我在这里阅读了支持的 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)
{
...
}
}