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?