2011-11-08 65 views
1

我有一個存儲過程,我傳遞一個值用於where子句中的select語句。Sql where子句

如果我傳遞的值是NULL,我不希望它成爲使用where子句的那部分的一部分。在下面的例子中,variable2是我傳遞給存儲過程並在sql語句中使用的變量,但如果@ variable2爲NULL,我不想在where子句中使用variable2 = @ val1。例如:

select Field1, Field2 from tbl1 
where variable2= @val1 
and ID = 'test' 

回答

0

嘗試:

where (@val1 is null or variable2 = @val1) 
and ID = 'test' 
0
select Field1, Field2 from tbl1 
where (variable2= @val1 or @val1 is null) 
and ID = 'test' 
0

如何:

select Field1, Field2 from tbl1 
where (@val1 IS NULL or variable2 = @val1) 
and ID = 'test' 
0

WHERE條款應在左側列,並可能可能是這樣的但你稱它爲variable2。這會工作,給出具體參數:

select Field1, Field2 
from tbl1 
where yourColumn = 
case 
    when @param1 is null 
    then @param2 
end 

我用一個通用的字段名稱和參數名稱,但你應該明白我的意思。