SqlDependency notification – 执行查询后立即失败通知

我有一个问题,我试图设置SqlDependency通知,以便在sql服务器上的表中的数据发生更改时接收通知。 但是,只要我执行用于设置sql depenency的查询,就会立即收到通知,指示由于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分析器)。

您必须在SQL select语句中为表使用两个部分名称(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查询通知 。

希望这可以帮助。