I am working on a stored procedure with several optional parameters. Some of these parameters are single values and it’s easy enough to use a WHERE clause like:
WHERE (@parameter IS NULL OR column = @parameter)
However, in some instances, the WHERE condition is more complicated:
WHERE (@NewGroupId IS NULL OR si.SiteId IN (SELECT gs.SiteId FROM [UtilityWeb].[dbo].[GroupSites] AS gs WHERE gs.GroupId = @NewGroupId))
When I uncomment these complicated WHERE clauses, the query execution time doubles and the execution plan becomes remarkably more complicated. While the execution plan doesn’t bother me, doubling the execution time of a query is a definite problem.
Is there a best practice or pattern that others have found for working with optional parameters in their stored procedures?
Is this one of those instances where dynamic SQL would be a better solution?
The main problem is likely to be parameter sniffing, and wildly different optimal execution plans depending on which of your parameters are NULL. Try running the stored proc with RECOMPILE.
Contrary to some beliefs, Sql Server does do short circuit evaluations – though (as with all query optimizations) it may not be exactly what you wanted.
BTW – I would probably rewrite that portion of the query as a JOINed derived table:
It may or may not influence the query plan, but it’s a bit cleaner to me.