同一参数中的空值和非空值

时间:2011-11-10 00:51:30

标签: sql sql-server-2008

我有这个:

Decalre @param int
select * from table where param = @param

有时人们想选择param为null的记录。

所以,像这样:

if @param is null
begin
select * from table where param is null
end
else select * from table where param =@param

是否可以将其合并到一个查询中?

3 个答案:

答案 0 :(得分:2)

应该能够在where子句中掩盖它:

select * from table where (param =@param) or (param is null and @param is null) 

答案 1 :(得分:1)

使用coalesce替换null值,性能会比我认为的or更好:

SELECT * 
FROM table 
WHERE Coalesce(@param, 1) = Coalesce(param, 1)

答案 2 :(得分:0)

select 
  * 
from table 
where (@param is null AND param is null) OR (@param is not null AND param = @param)