Stored Procedure Filter Tip
Ever see a stored procedure that uses its parameters to filter data? You’ve probably seen people use “If” statements to check for nulls, and write a separate query for each. That leads to an exponential number of branches, and can get out of hand quickly.
My solution, which seems to elude most people, is to do the following:
Select * From MyData Where (@MyParam Is Null Or MyColumn1 = @MyParam )
This method uses a simple “Or” statement to check for null. If the parameter is null, it is not used to filter the results. If you want to add more conditions, it is extremely easy, because you only need to add 1 extra line for each. Just be sure to use parenthesis so that the “And” and “Or” don’t get confusing.
Nice Tip!
I will start using this from today in some applications i am building these days.
Thanks for sharing…
I like the style and elegance of your solution which works great for me so far. Looking at alternatives it seems they are trying to use a sledgehammer to crack a nut - great job !
NICE !
Thank you so much!!! This is fact I was looking for for long time.
WORK LIKE A CHARM
Thanks again
I agree with Simon! Simple yet very useful!
THANKS
Hi….
Another version….
Select * From MyData Where MyColumn1 = ISNULL(@MyParam,MyColumn1)
Good Job..
Gianluca
Thank You! Excellent Tip!
This is a brilliant solution - Thanks!