代码之家  ›  专栏  ›  技术社区  ›  Matthew Vines

不允许使用WHERE子句的SqlDependency查询。如何将其修改为有效?

  •  3
  • Matthew Vines  · 技术社区  · 14 年前

    我使用以下查询设置了SqlDependency:

    string sql = "SELECT dbo.Case.CMRID, dbo.Case.SolutionID, dbo.Case.CreateDT, dbo.Case.ModifyDT "
    + "FROM dbo.Case "
    + "WHERE dbo.Case.ModifyDT > @LastExecutionDateTime";
    

    执行此查询将导致onchanged事件以 无效 和来源 陈述 . 经过进一步的研究,我发现当查询破坏与索引视图规则相同的规则时会发生什么情况,因为这就是此通知机制的基础。

    检查 Special Considerations Using Query Notifications (ADO.NET) 我看不出我违反了什么规则。

    将语句修改为

    string sql = "SELECT dbo.Case.CMRID, dbo.Case.SolutionID, dbo.Case.CreateDT, dbo.Case.ModifyDT "
    + "FROM dbo.Case";
    

    工作正常。onchanged事件仅在适当时激发,并设置了正确的类型。

    那么,如何才能只返回自上次执行语句以来具有修改日期的记录?

    3 回复  |  直到 10 年前
        1
  •  5
  •   Remus Rusanu    14 年前

    modifydt是什么类型的?

    QN的ADO.NET引用不完整,完整列表位于 Creating a Query for Notification . 后者还列出了以下内容:

    语句不能有比较 或基于double/real的表达式 数据类型。

    另一个问题可能是在查询中从字符串转换到datetime,这可能被认为是不确定的(ado.net和sql规范都列出了这一条件)。尝试改用类型化参数: WHERE ModifyDT > @lastDateTime 并传入datetime类型的参数。

        2
  •  2
  •   Mr. Graves    13 年前

    很明显你已经有了一个生成日期的东西

    上次执行日期时间

    因此,与其在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);
    
        3
  •  0
  •   Kelso Sharp    10 年前

    如果您还没有弄清楚,问题是3部分的表名,请这样尝试。

    "SELECT [CMRID], 
           [SolutionID], 
           [CreateDT], 
           [ModifyDT] 
    FROM [dbo].[Case] 
    WHERE [ModifyDT] > " + LastExecutionDateTime;