开发者

SQL Server Exists predicate

开发者 https://www.devze.com 2023-03-25 21:46 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号