CASE in WHERE, SQL Server

前端 未结 5 1845
南笙
南笙 2020-12-06 04:47

I\'m doing some search, where users are choosing in dropdown some clauses. When they leave some box empty, I want query to ignore clause. I know CASE, and best I thought of

5条回答
  •  没有蜡笔的小新
    2020-12-06 05:16

    A few ways:

    -- Do the comparison, OR'd with a check on the @Country=0 case
    WHERE (a.Country = @Country OR @Country = 0)
    
    -- compare the Country field to itself
    WHERE a.Country = CASE WHEN @Country > 0 THEN @Country ELSE a.Country END
    

    Or, use a dynamically generated statement and only add in the Country condition if appropriate. This should be most efficient in the sense that you only execute a query with the conditions that actually need to apply and can result in a better execution plan if supporting indices are in place. You would need to use parameterised SQL to prevent against SQL injection.

提交回复
热议问题