CASE IN statement with multiple values

后端 未结 4 1851
一整个雨季
一整个雨季 2020-12-15 03:15

Is there a way to make a CASE statement with an IN clause?

SELECT
CASE c.Number
IN (\'1121231\',\'31242323\') THEN 1
IN (\'234523\',\'2342423\') THEN 2
END A         


        
相关标签:
4条回答
  • 2020-12-15 03:42

    The question is specific to SQL Server, but I would like to extend Martin Smith's answer.

    SQL:2003 standard allows to define multiple values for simple case expression:

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

    It is optional feature: Comma-separated predicates in simple CASE expression“ (F263).

    Syntax:

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

    As for know I am not aware of any RDBMS that actually supports that syntax.

    0 讨论(0)
  • 2020-12-15 03:46

    If you have more numbers or if you intend to add new test numbers for CASE then you can use a more flexible approach:

    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;
    

    Also, instead of table variable you can use a regular table.

    0 讨论(0)
  • 2020-12-15 03:53

    Yes. You need to use the "Searched" form rather than the "Simple" form of the CASE expression

    SELECT CASE
             WHEN c.Number IN ( '1121231', '31242323' ) THEN 1
             WHEN c.Number IN ( '234523', '2342423' ) THEN 2
           END AS Test
    FROM   tblClient c  
    
    0 讨论(0)
  • 2020-12-15 03:53

    You can return the same value from several matches:

    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
    

    This will probably result in the same execution plan as Martins suggestion, so it's more a matter of how you want to write it.

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