我们可以传递null到sql参数来查询所有吗?

时间:2010-02-17 14:38:31

标签: .net sql sql-server sql-server-2005 tsql

我的查询如下

select * from table where col1 = @param1 and col2 = @parm2

另一个

select * from table where col1 = @param1

是否可以根据传递的参数在同一查询中执行两个操作,如果它是null查询全部或者当参数有值时选择它们。

我的查询非常大,我必须为每个创建2个sp版本,我想我可以尝试避免创建两个版本。

6 个答案:

答案 0 :(得分:2)

SELECT * from table where col1 = @param1 and col2 = isnull(@parm2, col2)

应该做你想要的。

答案 1 :(得分:1)

嗯,你可以试试这个,但我认为它不会很有效:

SELECT * FROM tab WHERE col1 = @param1 AND col2 = ISNULL(@parm2, col2)

答案 2 :(得分:1)

您可以尝试以下方式:

    select * from table where coalesce(@param1, col1) = col1 
and coalesce(@param2, col2) = col2

答案 3 :(得分:1)

此处有关使用COALESCE或ISNULL 的所有建议将有效 - 有效地执行此操作:

select *
from table
where (@param1 IS NULL OR col1 = @param1)
    and (@parm2 IS NULL OR col2 = @parm2)

您可能需要注意参数嗅探。 SQL Server 2005没有OPTIMIZE FOR UNKNOWN - 您可以将参数屏蔽到SP中的局部变量以帮助避免使用或使用RECOMPILE选项。

答案 4 :(得分:0)

这个怎么样:

select *
  from table
  where where (col1 = @param1 and col2 = @parm2)
  or (col1 = @param1 and parm2 is null)

答案 5 :(得分:0)

如果您使用存储过程!

IF Boolean_expression 
     { sql_statement | statement_block } 
[ ELSE 
     { sql_statement | statement_block } ] 

在您的方案中。

之类的东西
if (@param1 = null)
Begin
 select * from table where col2 = @parm2
( 
End

else if (@param1 = 'something' )
Begin
(
 select * from table where col1 = @param1
End

参考:http://msdn.microsoft.com/en-us/library/ms182717.aspx

相关问题