Link to home
Start Free TrialLog in
Avatar of SamCash
SamCashFlag for United States of America

asked on

MS SQL Conditional WHERE clause

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
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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...
Avatar of SamCash

ASKER

Scott,

Excellent, works perfectly!

Regards
Sam