Conditional Check in Where clause

前端 未结 2 1736
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 14:00

i have a procedure in which the below condition is to be written in a WHERE clause. How do I do that.

itemid is a parameter which can be null.

if itemid is avail

2条回答
  •  后悔当初
    2021-01-21 14:24

    Some people use this technique

    ... WHERE @itemid IS NULL OR tbl.itemid = @itemid
    

    It guarantees though that you will never get an index seek on the itemid column.

    A better approach if the table is at all big is to split the query up into 2 separate cases

    IF(@itemid IS NULL)
      SELECT foo FROM bar
    ELSE
      SELECT foo FROM bar WHERE itemid = @itemid
    

    If the number of combinations is too large you can consider dynamic SQL. Be sure you understand SQL injection first.

    Ref: Dynamic Search Conditions in T-SQL

提交回复
热议问题