I am working on a stored procedure with several optional parameters. Some of these parameters are single values, and simply use the WHERE clause, for example:
WHERE (@parameter IS NULL OR column = @parameter)
However, in some cases, the WHERE clause is more complex:
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 complex WHERE clauses, the query execution time doubles and the execution plan becomes much more complicated. Although the execution plan does not bother me, doubling the execution time of the request is a definite problem.
Is there a best practice or template that others have found to work with optional parameters in their stored procedures?
Is this one of those cases where dynamic SQL will be the best solution?