Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

sql server - Confusing null compares combined with NOT

I realize that comparing NULL to any other value (including NULL) will always result in false.

DECLARE @IsSet bit = NULL;

SELECT IIF(@IsSet = 1, 'true', 'false')
SELECT IIF(@IsSet != 1, 'true', 'false')

This outputs:

false
false

But this is part that confuses me:

SELECT IIF(NOT(@IsSet = 1), 'true', 'false')
SELECT IIF(NOT(@IsSet != 1), 'true', 'false')

This also outputs:

false
false

I would expect that the NOT would have flipped the value to TRUE. (Which it does if @IsSet is set to 0 for the first expression)

It seems that the compare to the null value has some power over the boolean logic outside the parenthesis.

But the null compare is not all powerful over boolean logic:

SELECT IIF((@IsSet = 1) OR (1=1), 'true', 'false')
SELECT IIF((@IsSet != 1) OR (1=1), 'true', 'false')

This returns:

true
true

I don't understand what is happening here, but I assume that this is done on purpose. But I don't know why.

Can someone explain why NOT(NULL!=1) does not equal true.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A comparison with NULL results in UNKNOWN rather than TRUE or FALSE. NOT UNKNOWN also results in UNKNOWN, which is neither TRUE nor FALSE. One cannot "flip" UNKNOWN to a Boolean value using NOT.

This 3-way logic requires one to use IS NULL or IS NOT NULL to test for NULL values rather than traditional Boolean logic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...