关于tsql:在T-SQL中测试不平等

关于tsql:在T-SQL中测试不平等

Testing for inequality in T-SQL

我刚刚在WHERE子句中遇到了这个问题:

1
AND NOT (t.id = @id)

与以下内容相比如何:

1
AND t.id != @id

或与:

1
AND t.id <> @id

我总是会自己写后者,但显然其他人的看法有所不同。一个人的表现会比另一个人好吗?我知道使用<>!=会使使用我可能拥有的索引的希望破灭,但是肯定上面的第一种方法会遇到同样的问题吗?


这3个将获得相同的确切执行计划

1
2
3
4
5
6
7
8
9
10
11
declare @id varchar(40)
select @id = '172-32-1176'

select * from authors
where au_id <> @id

select * from authors
where au_id != @id

select * from authors
where not (au_id = @id)

当然,这也将取决于索引本身的选择性。我总是自己使用au_id <> @id id


请注意!=运算符不是标准SQL。如果您希望代码具有可移植性(也就是说,如果您愿意的话),请改用<>。


以后再来的人只需稍作调整:

当存在空值时,等于运算符将生成未知值
未知值将被视为false
Not (unknown)仍然是unknown

在下面的示例中,我将询问一对(a1, b1)是否等于(a2, b2)
请注意,每列都有3个值:01NULL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
DECLARE @t table (a1 bit, a2 bit, b1 bit, b2 bit)

Insert into @t (a1 , a2, b1, b2)
values( 0 , 0 , 0 , NULL )

select
a1,a2,b1,b2,
case when (
    (a1=a2 or (a1 is null and a2 is null))
and (b1=b2 or (b1 is null and b2 is null))
)
then
'Equal'
end,
case when not (
    (a1=a2 or (a1 is null and a2 is null))
and (b1=b2 or (b1 is null and b2 is null))
)
then
'Not Equal'
end,
case when (
    (a1<>a2 or (a1 is null and a2 is not null) or (a1 is not null and a2 is null))
or (b1<>b2 or (b1 is null and b2 is not null) or (b1 is not null and b2 is null))
)
then
'Different'
end
from @t

请注意,在这里,我们期望的结果是:

  • 等于空
  • 不等于不等于
    平等的
  • 不同就不同

但是,相反,我们得到了另一个结果

  • 等于为空-我们所期望的。
  • 不等于为空???
  • 不同就是不同-我们所期望的。

不会影响性能,两个语句完全相等。

HTH


推荐阅读