我写SQL Server过程像下面如果SQL Server条件NULL检查
if @name_belongs_to != 'John'
begin
--doing some operation
end
如果名字不是“约翰”,这是工作的罚款。但是,如果它是NULL,它不会执行,如果部分。
如何处理?
我写SQL Server过程像下面如果SQL Server条件NULL检查
if @name_belongs_to != 'John'
begin
--doing some operation
end
如果名字不是“约翰”,这是工作的罚款。但是,如果它是NULL,它不会执行,如果部分。
如何处理?
一种选择是对名称中使用COALESECE()
:
if coalesce(@name_belongs_to, '') != 'John'
begin
--doing some operation
end
使用等于运算你不能比较的SQL Server(和大多数其他RDBMS)NULL
值。相反,您需要使用IS NULL
或IS NOT NULL
。使用COALESCE()
这里是一个技巧,它将NULL
的值转换为字符串,以便与!=
进行比较。
只使用不为空
if @name_belongs_to != 'John' or @name_belongs_to is not null
begin
--doing some operation
end
这也是正确的:
if @name_belongs_to != 'John' OR @name_belongs_to IS NULL
begin
--doing some operation
end
这MSDN article介绍如何三值逻辑的作品。
默认情况下,任何比较为null返回false
空= null是假
空= '值' 是假
,所以你需要添加
OR @name_belongs_to IS NULL
我在下面用声明来解决我的问题,
if isnull(@name_belongs_to,'') != 'John'
这是这是三种重要逻辑的症状,在这里阅读以获取更多信息; https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/ –