CASE IN statement with multiple values

后端 未结 4 1850
一整个雨季
一整个雨季 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: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.

提交回复
热议问题