The method suggested by djj55 only works if the column does not allow nulls.
Here is an example:
Code:
Declare @Fruit Table(Id Int Identity(1,1), Name VarChar(20))
Insert Into @Fruit(Name) Values('Apple')
Insert Into @Fruit(Name) Values('Banana')
Insert Into @Fruit(Name) Values('')
Insert Into @Fruit(Name) Values(NULL)
Insert Into @Fruit(Name) Values('Strawberry')
Select * From @Fruit
Declare @Name VarChar(20)
-- The following code selects just one row
Set @Name = 'Banana'
SELECT * FROM @Fruit WHERE Name LIKE ISNULL(@Name, '%')
-- The following code "should" select all rows, but doesn't because of the NULL in Row 6
Set @Name = NULL
SELECT * FROM @Fruit WHERE Name LIKE ISNULL(@Name, '%')
The technique of "WHERE (@customerId IS NULL OR customerId = @customerId)" always works. Unfortunately, this can cause havoc with unexpected things. The biggest problem with this code is that it is not sargable, so an index on the column would be ignored and you are left with an index scan instead of seek.
If you choose the IF/ELSE block method, looking for a single row would be sargable. Unfortunately, SQL may end up caching the execution plan with an index scan instead of seek, so you're no better off. This would be the old "Parameter Sniffing" problem.
As much as it sucks, there are a couple ways around this.
You could write separate stored procedures, one with the parameter and the other without it. Then, a 3rd procedure that looks like:
Code:
If @Parameter Is NULL
Exec Procedure_Without_Parameter
Else
Exec Procedure_With_Parameter @Parameter
This almost seems like a reasonable approach, until you start considering multiple optional parameters. Consider a procedure with 2 optional parameters. You would need 4 separate procedures. 3 parameters would be 8 procedures to handle all of he combinations. This quickly gets ugly.
Unfortunately, the best approach would be to use dynamic SQL. Done properly, it always returns the correct result and also performs as good as possible. For more reading on this:
-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom