I understand that this
开发者_开发知识库IF EXISTS(SELECT NULL) PRINT 'TRUE';
would always print TRUE
because after all NULL
is a value in SQL Server but why would this
IF EXISTS(SELECT NULL) PRINT 'TRUE'
print TRUE
as the sub query would cause an error and EXISTS
always checks for existence so how come this is possible.
Guessing because there is a copy/paste error in your question
EXISTS doesn't check for values. It checks for rows.
So these are valid because the SELECT gives one row
IF EXISTS(SELECT 1/0) PRINT 'TRUE'
IF EXISTS(SELECT NULL) PRINT 'TRUE';
IF EXISTS(SELECT CAST('fish' AS int)) PRINT 'TRUE';
To explain, we'll look at ANSI-92 SQL, search for "Query expressions 191
".
This is case 3a (my bold):
If the
<select list> "*"
is simply contained in a<subquery>
that is immediately contained in an<exists predicate>
, then the<select list>
is equivalent to a<value expression>
that is an arbitrary<literal>
.
So, this says you can have any old rubbish in the EXISTS bit: it should be ignored
精彩评论