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

前端 未结 5 1186
广开言路
广开言路 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:47

    Change from using the "or" syntax to a two query approach, you'll see 2 different plans that should keep your logical read count as low as possible:

    IF @MyOptionalParam is null
    BEGIN
    
      SELECT *
      FROM dbo.MyTableName t1
    
    END
    ELSE
    BEGIN
    
      SELECT *
      FROM dbo.MyTableName t1
      WHERE t1.MyField = @MyOptionalParam
    
    END
    

    You need to fight your programmer's urge to reduce duplication here. Realize you are asking for two fundamentally different execution plans and require two queries to produce two plans.

提交回复
热议问题