MS SQL Conditional WHERE clause

SamCash
SamCash used Ask the Experts™
on
If a parameter is not null, then include it in the WHERE clause.  I am trying to avoid a complex IF or CASE.  There are 8 @parameters, my example for simplicity has only 3.  In English, if a @paramX is null do not include it in the WHERE clause.

The following doesn't work (you can't have the "AND" in the IsNull function.  I am just trying to describe the goal.
SELECT *
FROM TableX
WHERE
   IsNull(@param1, AND @param1 = col1)
   IsNull(@param2, AND @param2 = col2)
   IsNull(@param3, AND @param3 = col3)

The following doesn't work either (there is no INCLUDE used this way.  I am just trying to describe the goal.
SELECT *
FROM TableX
WHERE
   IF @param1 IS NOT NULL INCLUDE "AND @param1 = col1"
   IF @param2 IS NOT NULL INCLUDE "AND @param2 = col2"
   IF @param3 IS NOT NULL INCLUDE "AND @param1 = col3"

I believe a complicated IF statements can solve this but with 8 @parameters I would have 256 IF statements with the correct WHERE clause in each one.  There must be an easier and simpler way to do this.  Easier to code, debug, test, and maintain.

Kind Regard
Sam
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior DBA
Most Valuable Expert 2018
Top Expert 2014
Commented:
Don't use ISNULL, it can be far less efficient.  Use this style instead:

WHERE
    (@param1 IS NULL OR @param1 = col1) AND
    (@param2 IS NULL OR @param2 = col2) AND
    ...
Mike EghtebasDatabase and Application Developer

Commented:
WHERE
@param1 = ISNULL(@param1, col1) AND
@param2 = ISNULL(@param2, col2) AND 
@param3 = ISNULL(@param3, col3) 

Open in new window


explanation:
When @param1 at line 2 is not null it is set to itself (@param1, meaning it rigors it). Otherwise it is set equal to col1.

edited...

Author

Commented:
Scott,

Excellent, works perfectly!

Regards
Sam

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial