你显然有一些东西可以生成日期
上次执行日期时间
因此,与其在 SQL 上创建 SqlDependency,不如使用 SqlCommand 对象
string sql = "SELECT CMRID, SolutionID, CreateDT, ModifyDT " + "FROM dbo.Case " + "WHERE ModifyDT > @lastExecutionDateTime";
//notice the parameter @lastExecutionDateTime, you cant use dates as a string, you also cant use something like CONVERT(datetime, '20040508'). You need a real date time object, hence the parameter
//You also only need to use the two part table ref (dbo.x) in the FROM clause, you dont need it on every field
//and while you didnt do it here, if anyone is interested a two part table ref in the form of dbo.[Case] would fail because the brackets will kill your dependency subscription
SqlCommand dependencyCommand= new SqlCommand(sql);
dependencyCommand.Parameters.Add(new SqlParameter("lastExecutionDateTime", SqlDbType.DateTime) {
Value = LastExecutionDateTime
});
然后只需创建对命令的依赖项
//Create a dependency object and associate it with the SqlCommand.
SqlDependency dependency = new SqlDependency();
dependency.AddCommandDependency(dependencyCommand);
//Subscribe to the SqlDependency event.
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
现在获取当前数据集并将其保存在内存中,以便您可以在依赖项触发时使用它进行比较
//get the most recent data
DataTable currentDependencyData = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(dependencyCommand);
dataAdapter.Fill(currentDependencyData);