2010-02-17 73 views
1

我有一个查询如下我们可以将null参数传递给sql参数来查询所有的参数吗?

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

而另一

select * from table where col1 = @param1 

是否有可能做基于参数相同的查询两种操作过去了,如果是空查询全部或者参数的值设为选择他们。

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

+1

使用isnull或coalesce可能会导致您的表上的表扫描。测试这种影响将是至关重要的,并可能影响您的决定取决于您的环境。 – 2010-02-17 15:58:03

+1

非常真实。 “简单代码”和性能之间的选择不应掉以轻心。 – 2010-02-17 16:42:25

+0

同意,我测试了两个并保持它们分开,并且它们比使用isnull,coalesce – 2010-02-17 17:10:22

回答

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

应该做你要找的东西。

1

好了,你可以试试这个,但我不认为这将是非常高性能:

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

你可以尝试这样的:

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

如何:

select * 
    from table 
    where where (col1 = @param1 and col2 = @parm2) 
    or (col1 = @param1 and parm2 is null) 
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

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选项。

相关问题