具有多个值的CASE IN语句

时间:2011-09-16 19:34:58

标签: sql sql-server sql-server-2005

有没有办法用IN子句创建CASE语句?

SELECT
CASE c.Number
IN ('1121231','31242323') THEN 1
IN ('234523','2342423') THEN 2
END AS Test
FROM tblClient c

4 个答案:

答案 0 :(得分:82)

是。您需要使用“搜索”表单而不是CASE表达式

的“简单”表单
SELECT CASE
         WHEN c.Number IN ( '1121231', '31242323' ) THEN 1
         WHEN c.Number IN ( '234523', '2342423' ) THEN 2
       END AS Test
FROM   tblClient c  

答案 1 :(得分:8)

您可以从多个匹配项中返回相同的值:

SELECT
  CASE c.Number
    WHEN '1121231' THEN 1
    WHEN '31242323' THEN 1
    WHEN '234523' THEN 2
    WHEN '2342423' THEN 2
  END AS Test
FROM tblClient c

这可能会导致与Martins建议相同的执行计划,所以更多的是你想如何编写它。

答案 2 :(得分:0)

该问题特定于SQL Server,但我想扩展Martin Smith's answer

SQL:2003标准允许为简单案例表达式定义多个值:

SELECT CASE c.Number
          WHEN '1121231','31242323' THEN 1
          WHEN '234523','2342423' THEN 2
       END AS Test
FROM tblClient c;

这是可选功能:Comma-separated predicates in simple CASE expression“ (F263)

语法:

CASE <common operand>
     WHEN <expression>[, <expression> ...] THEN <result>
    [WHEN <expression>[, <expression> ...] THEN <result>
     ...]
    [ELSE <result>]
END

据了解,我不知道任何实际支持该语法的RDBMS。

答案 3 :(得分:-1)

如果您有更多号码或者您打算为CASE添加新的测试号码,那么您可以使用更灵活的方法:

DECLARE @Numbers TABLE
(
    Number VARCHAR(50) PRIMARY KEY
    ,Class TINYINT NOT NULL
);
INSERT @Numbers
VALUES ('1121231',1);
INSERT @Numbers
VALUES ('31242323',1);
INSERT @Numbers
VALUES ('234523',2);
INSERT @Numbers
VALUES ('2342423',2);

SELECT c.*, n.Class
FROM   tblClient c  
LEFT OUTER JOIN   @Numbers n ON c.Number = n.Number;

此外,您可以使用常规表代替表变量。