Conditional Check in Where clause

前端 未结 2 1739
没有蜡笔的小新
没有蜡笔的小新 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:20

    e.g.

    SELECT Something
    FROM SomeTable
    WHERE (@MyParam IS NULL OR SomeField = @MyParam)
        AND AnotherField = 1
    

    You'll want to test this in your specific scenario for performance. If it's a simple query i.e. without a lot of conditional parameters, you might want to try this instead for performance:

    IF ( @MyParam IS NULL )
        SELECT Something
        FROM SomeTable
        WHERE AnotherField = 1
    ELSE
        SELECT Something
        FROM SomeTable
        WHERE SomeField = @MyParam 
            AND AnotherField = 1
    

提交回复
热议问题