简体   繁体   English

SQL Server 2005 - 在比较中使用Null

[英]SQL Server 2005 - Using Null in a comparison

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" 为什么我回到“1”而不是“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" 正确地给我回“0”

I know NULL comparisons can be tricky, but this particular example slipped through our code review process. 我知道NULL比较可能很棘手,但这个特殊的例子在我们的代码审查过程中滑落了。

Any clarifications would be greatly appreciated 任何澄清将不胜感激

This is because of 3 valued logic . 这是因为3值逻辑 In the first case Unknown does not evaluate to true so you end up in the else 在第一种情况下,Unknown不会评估为true,因此您最终会进入else

DECLARE @result BIT
SET @result = CASE WHEN Unknown THEN 0
                   ELSE 1
              END
PRINT @result

In the second case you are doing True or Unknown which evaluates to true. 在第二种情况下,您执行True或Unknown,其值为true。

DECLARE @result BIT
SET @result = CASE WHEN True
                        OR Unknown THEN 0
                   ELSE 1
              END
PRINT @result

This is due to the ANSI SQL standard and the behavior of comparison operators with NULL. 这是由于ANSI SQL标准和比较运算符的行为。 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. 每当您想要将值与可能为NULL的值进行比较时,您需要使用IS运算符来显式检查值可能为NULL的情况。 Or you can disable the ANSI_NULLS option in SQL Server. 或者,您可以在SQL Server中禁用ANSI_NULLS选项。

The following examples do what you want: 以下示例执行您想要的操作:

DECLARE @result BIT  
DECLARE @input INT

SET @input = NULL
SET @result = CASE WHEN (@input IS NULL OR @input <> 4) THEN 0  
                   ELSE 1  
              END  
PRINT @result  

Or this: 或这个:

SET ANSI_NULLS OFF

DECLARE @result BIT 
SET @result = CASE WHEN NULL <> 4 THEN 0 
                   ELSE 1 
              END 
PRINT @result 

References: 参考文献:

http://msdn.microsoft.com/en-us/library/ms188048.aspx http://msdn.microsoft.com/en-us/library/ms188048.aspx

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. 从纯技术角度来看,第一个语句返回1的原因是因为ANSI_NULLS设置为“ON”,它将NULL视为符合ISO标准的“未知”。

To have the values evaluate as you're expecting, run your script with SET ANSI_NULLS OFF ahead of it. 要按照您的预期评估值,请在其前面使用SET ANSI_NULLS OFF运行脚本。

In real life, of course, ISNULL() is the most awesome/safest approach. 当然,在现实生活中, ISNULL()是最棒的/最安全的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM