2016-06-13 167 views
2

我写SQL Server过程像下面如果SQL Server条件NULL检查

if @name_belongs_to != 'John' 
begin 
    --doing some operation 
end 

如果名字不是“约翰”,这是工作的罚款。但是,如果它是NULL,它不会执行,如果部分。

如何处理?

+3

这是这是三种重要逻辑的症状,在这里阅读以获取更多信息; https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/ –

回答

4

一种选择是对名称中使用COALESECE()

if coalesce(@name_belongs_to, '') != 'John' 
begin 
    --doing some operation 
end 

使用等于运算你不能比较的SQL Server(和大多数其他RDBMS)NULL值。相反,您需要使用IS NULLIS NOT NULL。使用COALESCE()这里是一个技巧,它将NULL的值转换为字符串,以便与!=进行比较。

0

只使用不为空

if @name_belongs_to != 'John' or @name_belongs_to is not null 
begin 
    --doing some operation 
end 
2

这也是正确的:

if @name_belongs_to != 'John' OR @name_belongs_to IS NULL 
begin 
    --doing some operation 
end 

MSDN article介绍如何三值逻辑的作品。

0

默认情况下,任何比较为null返回false

空= null是假
空= '值' 是假

,所以你需要添加

OR @name_belongs_to IS NULL 
0

我在下面用声明来解决我的问题,

if isnull(@name_belongs_to,'') != 'John'