我已经编写了如下SQL Server过程,
if @name_belongs_to != 'John'
begin
--doing some operation
end
如果这个名字不是"约翰",它就可以正常工作。但是,如果它为NULL,则它不会执行if部分。
如何处理?
一个选项是在名称上使用COALESECE()
:
if coalesce(@name_belongs_to, '') != 'John'
begin
--doing some operation
end
不能使用equals运算符比较SQL Server(以及大多数其他RDBMS)中的NULL
值。相反,您需要使用IS NULL
或IS NOT NULL
。这里使用COALESCE()
是一个技巧,它将把NULL
的值转换为字符串以与!=
进行比较。
这也是有效的:
if @name_belongs_to != 'John' OR @name_belongs_to IS NULL
begin
--doing some operation
end
这篇MSDN文章解释了三值逻辑是如何工作的。
只使用不为空
if @name_belongs_to != 'John' or @name_belongs_to is not null
begin
--doing some operation
end
默认情况下,任何与null的比较都会返回错误的
null=null为false
null="value"为false
所以你需要添加
OR @name_belongs_to IS NULL
我使用以下语句来解决我的问题,
if isnull(@name_belongs_to,'') != 'John'