views:

48

answers:

2

I have very long select query which i need to filter based on some params, i'm trying to avoid having different stored procedures or if statements inside of single stored procedure by using partly dynamic TSQL...

I will avoid long select just for example sake

select a
from b
where c=@c
or d=@d

@c and @d are filter params, only one can filter at the same time but also both filters could be disabled. 0 for each of these means param is disables so i can create nvarchar with where statement in it...

How do i integrate in here dynamic query so 'where' can be added to normal query. I cannot add all the query as big nvarchar because there is too many things in it which will require changes ( ie. when's, subqueries, joins)

+5  A: 

How about something like:

SELECT a
FROM b
WHERE (@c IS NULL OR c = @c)
AND (@d IS NULL OR d = @d)

When you're not using the filter, set the parameter to NULL and the condition should be short-circuited.

lc
+1 was going to suggest this exact thing
Andrew Barrett
omg,,,, why some ppl are so smart ...just one small question, how do i pass SqlParam with null from ASP.NET without getting an Exception ?This is how i set params : adp.SelectCommand.Parameters.Add("@c", SqlDbType.TinyInt).Value = someValue;
eugeneK
Don't set the parameter value when it has no value.
rdkleine
@rdkleine, thanks !!!
eugeneK
A: 

A little late but

 SELECT a  FROM b    
  WHERE c = isNULL(@c, c)  AND d=  isNULL(@d, d)  
ggonsalv