Note that there are some explanatory texts on larger screens.

plurals
  1. POProper way to handle 'optional' where clause filters in SQL?
    primarykey
    data
    text
    <p>Let's say you have a stored procedure, and it takes an optional parameter. You want to use this optional parameter in the SQL query. Typically this is how I've seen it done:</p> <pre><code>SELECT * FROM dbo.MyTableName t1 WHERE t1.ThisField = 'test' AND (@MyOptionalParam IS NULL OR t1.MyField = @MyOptionalParam) </code></pre> <p>This seems to work well, however it causes a high amount of logical reads if you run the query with STATISTICS IO ON. I've also tried the following variant:</p> <pre><code>SELECT * FROM dbo.MyTableName t1 WHERE t1.ThisField = 'test' AND t1.MyField = CASE WHEN @MyOptionalParam IS NULL THEN t1.MyField ELSE @MyOptionalParam END </code></pre> <p>And it yields the same number of high reads. If we convert the SQL to a string, then call sp_ExecuteSQL on it, the reads are almost nil:</p> <pre><code>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 </code></pre> <p>Am I crazy? Why are optional where clauses so hard to get right?</p> <p><strong>Update:</strong> I'm basically asking if there's a way to keep the standard syntax inside of a stored procedure and get low logical reads, like the sp_ExecuteSql method does. It seems completely crazy to me to build up a string... not to mention it makes it harder to maintain, debug, visualize..</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload