views:

2274

answers:

7

I'm trying to write a query for an advanced search page on my document archiving system. I'm attempting to search by multiple optional parameters. I have about 5 parameters that could be empty strings or search strings. I know I shouldn't have to check for each as a string or empty and create a separate stored procedure for each combination.

Edit: Ended up using:

ISNULL(COALESCE(@var, a.col), '') = ISNULL(a.col, '')
A: 

You can put OR's in your WHERE clause like so:

WHERE 
   (@var1 = '' OR col1 = @var1) AND
   (@var2 = '' OR col1 = @var2) AND
   (@var3 = '' OR col1 = @var3) ...
Dave Markle
While this solution will work, it's incredibly expensive. Don't use OR... instead use the ISNULL (example above).
Timothy Khouri
This solution will work in ALL cases. The IsNull/Coalesce solution will only work under controlled circumstances. When you use Coalesce, you are still testing for a column to EQUAL a value. If the value in the column is NULL, it will not be EQUAL and the row will NOT be returned.
G Mastros
A: 

You can pass optional parameters to a stored procedure but the optimizer will build a plan based on the specific calls you make to that proc. There are some tricks in SQL Server 2005 and later to avoid this (parameter sniffing, 'with no compile' hints, etc.)

Even with that, tho, I prefer to build a view with the core of the query and then use that view in several procs with the specific parameters. That allows SQL to optimize as it wants/should and I still get to consolidate the query specifics.

n8wrl
+7  A: 

You could use COALESCE (or ISNULL) like so:

WHERE COALESCE(@var1, col1) = col1 
AND COALESCE(@var2, col2) = col2 
AND COALESCE(@var3, col3) = col3
edosoft
This solution will not work if the column value is NULL because you cannot NULL cannot be tested that way. If the value is NULL, the row will be filtered out. This is not what you want.
G Mastros
A: 

Even better is to make the parameter optional NULL and then test in the WHERE clause just like the empty string case...

Dining Philanderer
+3  A: 

I usually do this :P

WHERE (@var1 IS NULL OR col1 = @var1) AND (@var2 IS NULL OR col2 = @var2) ...

clyc
+1  A: 

An alternative is to dynamically built the SQL in the Stored Procedure, this produces the best possible plan for the query and a plan will be created and used anyway (in 2005 and above).

Coolcoder
A: 

Hello there,

Thank you very very much!!!. it works for me. Thanks a lot