Checking an input param if not Null and using it in where in SQL Server

Martin picture Martin · Nov 19, 2010 · Viewed 51.3k times · Source

What is the best way to include an input param in the WHERE clause but exclude it if it is null?

There are a number of ways I believe, but I can't seem to remember then.

Also could I use the COALESCE()? But I think this is only for SELECTing values?

Edit

To clarify, let's say a variable called @code ="1" then my where would be Where type='B' AND code = @code but if @code is null then I only want Where type='B' - notice the missing code = @code.

Answer

Klaus Byskov Pedersen picture Klaus Byskov Pedersen · Nov 19, 2010

You can use IsNull

 where some_column = IsNull(@yourvariable, 'valueifnull')

EDIT:

What you described in the comment can be done like:

where (@code is null or code = @code)