相结合的混淆空值比较

相结合的混淆空值比较

本文介绍了与 NOT 相结合的混淆空值比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到将 NULL 与任何其他值(包括 NULL)进行比较总是会导致错误.

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')

输出:

false
false

但这是让我困惑的部分:

But this is part that confuses me:

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

这也输出:

false
false

我希望 NOT 会将值翻转为 TRUE.(如果第一个表达式的 @IsSet 设置为 0,它会这样做)

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')

返回:

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.

谁能解释一下为什么 NOT(NULL!=1) 不等于 true.

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

推荐答案

NULL 的比较导致 UNKNOWN 而不是 TRUE 或 .NOT UNKNOWN 也会导致 UNKNOWN,它既不是 TRUE 也不是 FALSE.不能使用 NOTUNKNOWN翻转"为布尔值.

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.

此三路逻辑需要使用 IS NULLIS NOT NULL 用于测试 NULL 值而不是传统的布尔逻辑.

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

这篇关于与 NOT 相结合的混淆空值比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 09:03