Sql 当值可以同时为NULL或text时进行比较
现在我知道您不能直接将NULL与任何东西进行比较(因为NULL是未知的),那么我如何实现以下目标:Sql 当值可以同时为NULL或text时进行比较,sql,sql-server,sql-server-2005,tsql,Sql,Sql Server,Sql Server 2005,Tsql,现在我知道您不能直接将NULL与任何东西进行比较(因为NULL是未知的),那么我如何实现以下目标: select * from Material as m where MtrlCode = 826 and Exposlimit <> 'compareMe' 选择* 从材料到材料 其中MtrlCode=826和 exposeLimit“compareMe” 其中Exposlimit可以为NULL,也可以不为NULL。 “compa
select *
from Material as m
where MtrlCode = 826 and
Exposlimit <> 'compareMe'
选择*
从材料到材料
其中MtrlCode=826和
exposeLimit“compareMe”
其中Exposlimit可以为NULL,也可以不为NULL。
“compareMe”也可以为空
因此,我如何比较两者?两边都可以是文本或NULL。select*
select *
from Material as m
where (MtrlCode = 826 or MtrlCode IS NULL) and
(Exposlimit <> 'compareMe' or Exposlimit IS NULL)
从材料到材料
其中(MtrlCode=826或MtrlCode为空)和
(Exposlimit“compareMe”或Exposlimit为空)
在这种情况下使用IFNULL函数
i、 e
其中IFNULL(FieldA,'MagicConstant')=IFNULL(FieldB,'MagicConstant')select*
从材料到材料
其中MtrlCode=826
和(Exposlimit'compareMe'
或(Exposlimit为null,compareme不为null)
或者(Exposlimi不为null,compareme为null))
你试过这个吗
select *
from Material as m
where MtrlCode = 826 and
Exposlimit IS NOT NULL AND 'compareMe' IS NOT NULL AND Exposlimit <> 'compareMe'
选择*
从材料到材料
其中MtrlCode=826和
Exposlimit不为NULL且“compareMe”不为NULL且Exposlimit“compareMe”
考虑到更容易找到平等:
(Column = @Value or (Column is null and @Value is null))
当两个值相等时,结果为true。
理想情况下,我们可以否定这个语句来发现不平等性,但是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
T-SQL中是否存在IFNULL?即使您使用ISNULL,优化器也很难使用您定义的任何索引。@Paul,是的,sql server没有基于函数的索引,解决方法()看起来非常难看。
CASE WHEN Column is null and @Value is null or Column = @Value THEN 1 ELSE 0 END = 0