SQL Server 2005 - 在比较中使用 Null
这更多是为了满足自己的好奇心而提出的问题。给出以下语句:
DECLARE @result BIT
SET @result = CASE WHEN NULL <> 4 THEN 0
ELSE 1
END
PRINT @result
为什么我返回“1”而不是“0”
将其更改为:
DECLARE @result BIT
SET @result = CASE WHEN NULL IS NULL
OR NULL <> 4 THEN 0
ELSE 1
END
PRINT @result
正确地返回“0”
我知道 NULL 比较可能很棘手,但这个特定的示例溜过了我们的代码审查过程。
任何澄清将不胜感激
This is more of a question to satisfy my own curiosity. Given the following statement:
DECLARE @result BIT
SET @result = CASE WHEN NULL <> 4 THEN 0
ELSE 1
END
PRINT @result
Why do i get back "1" instead of "0"
Changing it to:
DECLARE @result BIT
SET @result = CASE WHEN NULL IS NULL
OR NULL <> 4 THEN 0
ELSE 1
END
PRINT @result
Correctly gives me back "0"
I know NULL comparisons can be tricky, but this particular example slipped through our code review process.
Any clarifications would be greatly appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为 三值逻辑。在第一种情况下,Unknown 不会评估为 true,因此您最终会处于 else 状态。
在第二种情况下,您正在执行 True 或 Unknown,其评估结果为 true。
This is because of 3 valued logic. In the first case Unknown does not evaluate to true so you end up in the else
In the second case you are doing True or Unknown which evaluates to true.
这是由于 ANSI SQL 标准以及 NULL 比较运算符的行为。每当您想要将一个值与可能为 NULL 的值进行比较时,您需要使用 IS 运算符来显式检查该值是否可能为 NULL。或者您可以禁用 SQL Server 中的 ANSI_NULLS 选项。
以下示例可以满足您的要求:
或者这样:
参考:
http://msdn .microsoft.com/en-us/library/ms188048.aspx
This is due to the ANSI SQL standard and the behavior of comparison operators with NULL. Whenever you want to compare a value with a value that could be NULL, you need to use the IS operator to explicitly check for the case where the value could be NULL. Or you can disable the ANSI_NULLS option in SQL Server.
The following examples do what you want:
Or this:
References:
http://msdn.microsoft.com/en-us/library/ms188048.aspx
从纯粹的技术角度来看,第一个语句返回 1 的原因是因为 ANSI_NULLS 设置为“ON”,将 NULL 视为遵循 ISO 标准的“未知”。
要使值按照您的预期进行评估,请在脚本前面加上
SET ANSI_NULLS OFF
来运行脚本。当然,在现实生活中,ISNULL() 是最棒/最安全的方法。
From a purely technical perspective, the reason why the first statement returns a 1 is because ANSI_NULLS is set to "ON" which treats NULL as "Unknown" which follows the ISO standard.
To have the values evaluate as you're expecting, run your script with
SET ANSI_NULLS OFF
ahead of it.In real life, of course,
ISNULL()
is the most awesome/safest approach.