简体   繁体   中英

Can we pass null to sql parameter to query all?

I have a query as follows

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

And another

select * from table where col1 = @param1

Is it possible do both operations in same query based on parameter passed, if it is null query all or when parameter has value select them.

My queries are very big and i have to create 2 versions of sp's for each and i was thinking that can i try to avoid creating two.

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

应该做你想要的。

好吧,您可以尝试一下,但是我认为它的性能不是很高:

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

You could try something like:

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

All the suggestions here about using COALESCE or ISNULL will work - effectively doing this:

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

But you may need to watch out for parameter sniffing. SQL Server 2005 does not have the OPTIMIZE FOR UNKNOWN - you can mask the parameters into local variables in the SP to help avoid that or use RECOMPILE option.

How about this:

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

If you use Stored procedures!

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

In your scenario. something like

if (@param1 = null)
Begin
 select * from table where col2 = @parm2
( 
End

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM