问题
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.
回答1:
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.
回答2:
The way you are using NOT is not correct. You'll get error, If you only execute the NOT condition as follows:
SELECT NOT(@IsSet = 1)
When you enclose your incorrect usage of NOT condition inside IIF condition, SQL server won't show you the error, However the statement will be evaluated to false output.
If you want to explicitly check for NULL value, then following practice can be adopted.
SELECT IIF(@IsSet IS NULL, 'true', 'false')
Lastly, the following condition is returning 'true' in output, because one of the OR condition (1==1) is always evaluating to 'true', hence the overall output of the IIF statement is true.
SELECT IIF((@IsSet = 1) OR (1=1), 'true', 'false')
SELECT IIF((@IsSet != 1) OR (1=1), 'true', 'false')
来源:https://stackoverflow.com/questions/50917922/confusing-null-compares-combined-with-not