Sylvain Lafontaine (sylvain aei ca (fill the blanks, no spam please))
writes:
[quoted text, click to view] > Take a look at the following examples:
>
> SELECT *
> FROM Employee
> WHERE EmployeeID = Coalesce (@EmployeeID, EmployeeID)
>
> SELECT *
> FROM Employee
> WHERE EmployeeID = Case when @EmployeeID is Null then EmployeeId else
> @EmployeeID End
>
> SELECT *
> FROM Employee
> WHERE ((EmployeeID = @EmployeeID) or (@EmployeeID is Null))
>
> The first one is usually the preferred one and should give you the best
> execution plan along with the second. I think that the last one might
> give a bad execution plan on many occasions but I'm not sure.
All three will scan the Employees table, and this is a suboptimal
plan, when a explicit id is given. Of course, if there is no index
on EmployeeID, this is not an issue.
Of these three, the first two has a gotcha, which is a good reason to
stay away from them: they do not work with nullable columns. It it is
not likely to matter here, since EmployeeID is likely to be a key and
not nullable. But assume that there is one more condition:
SELECT ...
FROM Employee
WHERE EmployeeID = coalesce(@EmployeeID, EmployeeID)
AND ShoeSize = coalesce(@ShoeSize, ShoeSize)
The user performs enters an employee id, without specifying a shoe size.
To his surprise, no data is returned. To wit, no shoe size had been
entered for this employee. Writing the query as:
SELECT ...
FROM Employee
WHERE (EmployeeID = @EmployeeID OR @EmployeeID IS NULL)
AND (ShoeSize = @ShoeSize OR @ShoeSizeIS NULL)
evades this problem.
--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx Books Online for SQL Server 2000 at