2011-11-08 295 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 

我用一个通用的字段名称和参数名称,但你应该明白我的意思。