【问题标题】:SqlDependency notification - immediate failure notification after executing querySqlDependency 通知 - 执行查询后立即通知失败
【发布时间】:2011-10-30 18:31:01
【问题描述】:

我在尝试设置 SqlDependency 通知以在 sql server 上的表中的数据发生更改时接收通知时遇到问题。但是,只要我执行用于设置 sql 依赖的查询,就会立即收到一条通知,指出由于 sql 语句的问题,订阅尝试失败 (SqlNotificationEventArgs shows Info: Invalid, Source: Statement, Type: Subscribe)

这表明我的 sql 查询存在问题,但尝试了一个非常基本的示例以确保 select 语句没有问题,我仍然会立即收到这些“无效”通知。我还确保我已经启动了 SQL Server 的服务代理,创建了一个队列和通知服务,并向主体授予了所有必要的权限(在这种情况下,我连接到 sql server 的用户) 这是我的桌子:

CREATE TABLE [dbo].[TableTest](
    [id] [int] NOT NULL,
    [val1] [int] NULL,
    [val2] [int] NULL,
   CONSTRAINT [PK_TableTest] PRIMARY KEY CLUSTERED ( [id] ASC )
) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

代码如下:

 SqlDependency.Start(connectStr);
 _connection = new SqlConnection(connectStr);
 _connection.Open();
 _sqlCommand = new SqlCommand("Select [id] from TableTest", _connection);
 _sqlCommand.Notification = null;
 SqlDependency dependency = new SqlDependency(_sqlCommand);
 dependency.OnChange += this.OnDataChangeNotification;

 DataTable dt = new DataTable();
 dt.Load(_sqlCommand.ExecuteReader());

在调用“_sqlCommand.ExecuteReader()”后,会立即使用显示 Info:Invalid、Source:Statement、Type:Subscribe 的 SqlNotificationEventArgs 参数调用 OnDataChangeNotification 处理程序。

任何人都知道问题可能是什么或如何确定/调试问题(不使用我没有 atm 的 SQL 分析器)。

【问题讨论】:

    标签: c# .net sql-server-2005 sql-server-2008 ado.net


    【解决方案1】:

    您必须在 SQL 选择语句中为您的表使用两个部分名称 (dbo.TableName) 才能使用 SqlDependency 通知:

    SqlDependency.Start(connectStr); 
    _connection = new SqlConnection(connectStr); 
    _connection.Open(); 
    _sqlCommand = new SqlCommand("Select [id] from dbo.TableTest", _connection); 
    _sqlCommand.Notification = null; 
    SqlDependency dependency = new SqlDependency(_sqlCommand); 
    dependency.OnChange += this.OnDataChangeNotification; 
    

    这里是查询通知要求的链接:MSDN Query Notifications

    希望,这会有所帮助。

    【讨论】:

    • 就是这样。非常感谢!还有一个问题,有没有办法确定哪些行实际被更改了?
    • @mike01010:据我所知,SqlDependency 类不提供跟踪更改的功能。
    • 但是如果您知道要查找的内容,您可以立即执行查询来查找更改。 (例如,如果时间戳在更改中更新,您可以查找最近的时间戳)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2020-11-27
    相关资源
    最近更新 更多