简体   繁体   English

在where子句中使用等于和IN的CASE语句

[英]CASE Statement in where clause using equal to and IN

WHERE CONDITION1='ABC'
AND Status =
    CASE  @Option 
            WHEN 1 THEN 'True'
            WHEN 2 THEN 'False'
            WHEN 3 THEN  NULL
            WHEn 4 THEN **IN ('True', 'False', NULL)**
    END

How do I write a query where my first options match directly using = but my last option needs an IN 如何编写查询,其中第一个选项使用=直接匹配,但最后一个选项需要IN

The above query gives error, but I want something similar to it, which I am not able to find out. 上面的查询给出了错误,但是我想要类似的东西,但我找不到。

A CASE statement can't return a set of values... but this query should give you the same results: CASE语句无法返回一组值...但是此查询应为您提供相同的结果:

WHERE CONDITION1='ABC'
AND Status =
    CASE  
        WHEN 1 THEN 'True'
        WHEN 2 THEN 'False'
        WHEN 3 THEN NULL
        WHEN 4 THEN Status
    END

Also, note that unless you have ANSI_NULLS OFF , Status will never = NULL ... you would need to use IS NULL for this comparison, and you'd need to forgo the CASE statement altogether. 另外,请注意,除非您具有ANSI_NULLS OFF ,否则Status永远不会= NULL ...您将需要使用IS NULL进行此比较,并且您将完全放弃CASE语句。

Skip the CASE statement and use OR. 跳过CASE语句并使用OR。 And as per ANSI standard don't compare with NULL : 而且根据ANSI标准, 请勿将NULL与NULL进行比较

WHERE CONDITION1='ABC'
AND ((@Option = 1 AND Status = 'True') OR
     (@Option = 2 AND Status = 'False') OR
     (@Option = 3 AND Status IS NULL) OR
     (@Option = 4 AND (Status IS NULL OR Status IN ('True', 'False'))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM