The following query works fine with SQLDependency (e.g., as passed to ExecuteNonQuery in this question):
SELECT SomeColumn
FROM dbo.SomeTable
WHERE Col1 = 'Foo'
AND Col2 = 'Bar'
Unfortunately, it appears that ExecuteNonQuery fetches all the matching rows to the client, even though it only returns an integer. The above query returns far too much data, so I need to reduce the number of matching rows. To that end, I changed the above to the following:
SELECT SomeColumn
FROM dbo.SomeTable
WHERE Col1 = 'Foo'
AND Col2 = 'Bar'
AND DateTimeUtc >= '2013-12-01 12:00:00'
(Note that the column DateTimeUtc is of type DateTime2.)
However, this doesn't work: the SqlDependency OnChange handler is immediately called with SqlNotificationEventArgs having properties Info=Invalid, Source=Statement, and Type=Subscribe.
I'm aware there are restrictions on what such a query may be, but as far as I can tell, the above doesn't violate any of these? Unless DateTime2 somehow qualifies as a 'double/real' for the restriction "The statement must not have comparison or expression based on double/real data types"?
Although this doesn't answer why the query was invalid, I've found a different query that works and doesn't return a lot of data to the client. As suggested by this post, you can use COUNT_BIG(*) without a GROUP_BY, even though the documentation linked above suggests otherwise! That is, the following works: