在Sql中进行NULL检查

时间:2012-10-19 15:26:08

标签: sql sql-server

请建议最新区别:

1)WHERE student.name = ISNULL(@name, student.name)

2)WHERE (student.name = @name OR @name IS NULL)

实际上我在我的名字上分配了一个问题错误,其中一些记录在我使用第一种方法时跳过了。但是当我用例如2替换它时得到纠正。

6 个答案:

答案 0 :(得分:8)

ISNULL()的{​​{3}}是替换值,表示如果第一个参数为null,将替换的值。因此,如果@namestudent.name都是null,那么您基本上就是写作:

student.name = NULL

等同于false(在SQL中为null被认为是未知的,并且从不等于任何东西。)

在第二个中,您使用IS运算符来测试空值,如果true为空,则返回@name

答案 1 :(得分:1)

第二个语句说当学生姓名与@name匹配或未指定姓名时选择记录如果指定了@name,请选择该名称。如果@name为空,请选择所有记录。当@name为NULL

时,这并不关心表中的值

对于第一个语句,如果@name为NULL,它将使用student.name,它与当前行的student.name

相同

当@name和student.name都为NULL

WHERE student.name = @name OR @name IS NULL -- the other part of the OR is true so records will be returned

WHERE student.name = ISNULL(@name, student.name) becomes WHERE NULL = NULL

因为NULL = NULL返回false,所以不会为该行返回任何记录

答案 2 :(得分:1)

WHERE student.name = ISNULL(@name, student.name)

WHERE (student.name = @name OR @name IS NULL)
除非student.name为null,否则

是等效的。

WHERE (student.name = @name OR @name IS NULL)

可能会简化:

WHERE COALESCE(student.name,'nul') = COALESCE(@name, student.name,'nul')

WHERE student.name = ISNULL(@name, student.name)

相当于

WHERE (student.name = @name OR @name IS NULL AND student.name IS NOT NULL)

答案 3 :(得分:1)

这是差异

name |student.name  |first_result  |second_result |expected*
A    |A             |true          |true          |true
A    |B             |false         |false         |false
null |A             |true          |true          |true
A    |null          |false         |false         |false
null |null          |FALSE         |TRUE          |TRUE

*预期 - 有些人期望,但在我们的宇宙中不正确。

如您所见,当两个值都为NULL时会出现差异,因为在这种情况下,您的第一个WHERE计算结果为: null = null(为FALSE)。

您可以在SQL Server中使用以下命令检查:

select case when null = null then 1 else 0 end

会给你0。

答案 4 :(得分:0)

如果您设置了ANSI_NULLS系统设置,则null = anything为false。

因此,即使student.name为空,第一个查询也不会返回@name为空的任何条目,因为对于student.name为null的条目,比较计算为where null=null,并且null=null返回false

答案 5 :(得分:0)

检查下面的示例,在第二个选项中,您可以在检查name = @name。

之前检查@name是否为空
declare @name varchar(10) = null
declare @table table (name varchar(10))

insert into @table 
select 'A'
UNION
SELECT null


---returns only A because null = column is always false
select * from @table where name = ISNULL(@name, name)

--returns all rows
select * from @table where (@name is null or name = @name)


set @name = 'A'
select * from @table where name = ISNULL(@name, name)
select * from @table where (@name is null or name = @name)