Proper way to handle 'optional' where clause filters in SQL?

前端 未结 5 1167
广开言路
广开言路 2020-12-31 23:12

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 don

5条回答
  •  耶瑟儿~
    2020-12-31 23:50

    If we convert the SQL to a string, then call sp_ExecuteSQL on it, the reads are almost nil...

    1. Because your query is no longer evaluating an OR, which as you can see kills sargability
    2. The query plan is cached when using sp_executesql; SQL Server doesn't have to do a hard parse...

    Excellent resource: The Curse & Blessing of Dynamic SQL

    As long as you are using parameterized queries, you should safe from SQL Injection attacks.

提交回复
热议问题