我剛剛碰到這樣的WHERE子句中:測試在T-SQL不平等
AND NOT (t.id = @id)
這怎麼比較:
AND t.id != @id
或用:
AND t.id <> @id
我總是自己寫後者,但顯然有人認爲是不同的。一個人會比另一個人表現得更好嗎?我知道使用<>
或!=
會破壞使用我可能擁有的索引的任何希望,但肯定是上面的第一種方法會遭受同樣的問題?
我剛剛碰到這樣的WHERE子句中:測試在T-SQL不平等
AND NOT (t.id = @id)
這怎麼比較:
AND t.id != @id
或用:
AND t.id <> @id
我總是自己寫後者,但顯然有人認爲是不同的。一個人會比另一個人表現得更好嗎?我知道使用<>
或!=
會破壞使用我可能擁有的索引的任何希望,但肯定是上面的第一種方法會遭受同樣的問題?
這3會得到同樣的確切的執行計劃
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自己
如何做這些條款處理空值?他們都是等同的嗎? – FistOfFury 2012-11-20 19:32:38
不會有性能問題,兩種說法完全平等。
HTH
請注意,!=運算符不是標準SQL。如果你想要你的代碼是可移植的(也就是說,如果你在意的話),請改用<>。
只是一個小adjustement FORS那些誰晚一點:
等於運算符產生不明的值時,有一個空 和未知的值將被視爲假。 未知(未知)未知
在下面的例子中,我會試着說一對夫婦(a1,b1)是否等於(a2,b2)。 請注意,每列有3個值0,1和NULL。
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
注意,這裏我們期望的結果:
,但我們得到的另一個結果
這應該是正確的答案 – 2013-11-04 01:47:37
參見:http://stackoverflow.com/questions/723195/should-i-use-or-for-not-equal-in-tsql – Dinah 2009-05-12 15:55:09