this is one of the few times when (In my opinion) dynamic SQL is the best way to go:If you has multiple conditions like that (which is a pretty common webform type requirement), then a construct like this:DECLARE @optionalParam1 INT = 4 , @optionalParam2 INT = NULL , @optionalParam3 CHAR(4) = NULL DECLARE @sql NVARCHAR(MAX) = N'SELECT mt.[foo] AS [bar] , mt.[woo] AS [shoo]FROM dbo.myTable AS mtWHERE 1 = 1'IF @optionalParam1 IS NOT NULL SET @sql += N' AND mt.[Column1] = @optionalParam1'IF @optionalParam2 IS NOT NULL SET @sql += N' AND mt.[Column2] = @optionalParam2'IF @optionalParam3 IS NOT NULL SET @sql += N' AND mt.[Column3] = @optionalParam3'PRINT @sql-- Do itEXEC sp_executesql @sql , N'@optionalParam1 INT , @optionalParam2 INT , @optionalParam3 CHAR(4)' , @optionalParam1 , @optionalParam2 , @optionalParam3
Will generate a reusable plan for each permutation of the search.Charlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION