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
Microsoft SQL ServerMicrosoft SQL Server 2008SQL

Avatar of undefined
Last Comment
SamCash
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

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
SamCash
Flag of United States of America image

ASKER

Scott,

Excellent, works perfectly!

Regards
Sam
Microsoft SQL Server
Microsoft SQL Server

Microsoft SQL Server is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.SQL Server is available in multiple versions, typically identified by release year, and versions are subdivided into editions to distinguish between product functionality. Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning.

171K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo