CASE in WHERE, SQL Server

前端 未结 5 1814
南笙
南笙 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:11

    You can simplify to:

    WHERE a.Country = COALESCE(NULLIF(@Country,0), a.Country);
    
    0 讨论(0)
  • 2020-12-06 05:11

    Try this:

    WHERE a.Country = (CASE WHEN @Country > 0 THEN @Country ELSE a.Country END)
    
    0 讨论(0)
  • 2020-12-06 05:12

    (something else) should be a.Country

    if Country is nullable then make(something else) be a.Country OR a.Country is NULL

    0 讨论(0)
  • 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.

    0 讨论(0)
  • .. ELSE a.Country ...
    

    I suppose

    0 讨论(0)
提交回复
热议问题