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

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

    This is another variation on the optional parameter technique:

    SELECT * FROM dbo.MyTableName t1
    WHERE t1.ThisField = 'test'
    AND t1.MyField = COALESCE(@MyOptionalParam, t1.MyField)
    

    I'm pretty sure it will have the same performance problem though. If performance is #1 then you'll probably be stuck with forking logic and near duplicate queries or building strings which is equally painful in TSQL.

提交回复
热议问题