2010-10-06 41 views
5

现在我知道你不能直接比较NULL任何东西(如空是未知的),所以我将如何实现以下目标:比较当值可以是两个NULL或文本

select * 
    from Material as m 
    where MtrlCode = 826 and 
      Exposlimit <> 'compareMe' 

凡Exposlimit可以为null或者它可能不是。 'compareMe'也可能为NULL。

因此我如何比较两者?双方都可以是文本或NULL。

回答

5
select * 
from Material as m 
where MtrlCode = 826 
    and (Exposlimit <> 'compareMe' 
     or (Exposlimit is null and compareme is not null) 
     or (Exposlimi is not null and compareme is null)) 
+0

精美的作品,非常感谢。 – 2010-10-06 13:24:56

1
select * 
    from Material as m 
    where (MtrlCode = 826 or MtrlCode IS NULL) and 
      (Exposlimit <> 'compareMe' or Exposlimit IS NULL) 
2

对这种情况使用IFNULL功能。

WHERE IFNULL(FIELDA, 'MagicConstant')= IFNULL(FieldB, 'MagicConstant')

+0

T-SQL中是否存在IFNULL?即使您使用ISNULL,优化器也会努力使用您可能定义的任何索引。 – 2010-10-06 12:10:46

+0

@Paul,是sql-server没有基于函数的索引,并且解决方法(http://www.sqlservercentral.com/scripts/T-SQL+Aids/31906/)看起来非常难看。 – 2010-10-06 12:21:21

0

你试试这个?

select * 
    from Material as m 
    where MtrlCode = 826 and 
      Exposlimit IS NOT NULL AND 'compareMe' IS NOT NULL AND Exposlimit <> 'compareMe' 
0

考虑,这是更容易找到平等:

(Column = @Value or (Column is null and @Value is null)) 

在双方的值相等,导致真实的。 我们从理论上是能够否定这个说法找到差距,但是SQL的三态逻辑打破了主意,因为NOT(UNKNOWN) = UNKNOWN

--DO NOT USE, broken 
NOT (Column = @Value or (Column is null and @Value is null)) 

因此,如果我们检查只有TRUE价值,否定它,我们仍然以可读的操作结束。

CASE WHEN Column is null and @Value is null or Column = @Value THEN 1 ELSE 0 END = 0