Say you have a stored procedure, and it takes an optional parameter. You want to use this optional parameter in an SQL query. This is usually how I saw it:
SELECT * FROM dbo.MyTableName t1 WHERE t1.ThisField = 'test' AND (@MyOptionalParam IS NULL OR t1.MyField = @MyOptionalParam)
It seems to work well, however it does cause a lot of logical readings if you run the query using STATISTICS IO ON. I also tried the following option:
SELECT * FROM dbo.MyTableName t1 WHERE t1.ThisField = 'test' AND t1.MyField = CASE WHEN @MyOptionalParam IS NULL THEN t1.MyField ELSE @MyOptionalParam END
And it gives the same amount of high readings. If we convert SQL to a string, then call sp_ExecuteSQL on it, the read numbers are almost zero:
DECLARE @sql nvarchar(max) SELECT @sql = 'SELECT * FROM dbo.MyTableName t1 WHERE t1.ThisField = ''test''' IF @MyOptionalParam IS NOT NULL BEGIN SELECT @sql = @sql + ' AND t1.MyField = @MyOptionalParam ' END EXECUTE sp_ExecuteSQL @sql, N'@MyOptionalParam', @MyOptionalParam
I've gone crazy? Why is it optional when clauses are so difficult to obtain?
Update: I basically ask if there is a way to keep the standard syntax inside the stored procedure and get low logical reads, like the sp_ExecuteSql method does. It seems completely crazy to me to create a chain ... not to mention the fact that it is more difficult to maintain, debug, visualize ..
optimization sql
Nicholas head
source share