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.
   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.
   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
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott PletcherSenior DBACommented:
Don't use ISNULL, it can be far less efficient.  Use this style instead:

    (@param1 IS NULL OR @param1 = col1) AND
    (@param2 IS NULL OR @param2 = col2) AND

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike EghtebasDatabase and Application DeveloperCommented:
@param1 = ISNULL(@param1, col1) AND
@param2 = ISNULL(@param2, col2) AND 
@param3 = ISNULL(@param3, col3) 

Open in new window

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.

SamCashAuthor Commented:

Excellent, works perfectly!

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.