Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL CASE multiple Conditions same Result

i need in SQL the equivalent C# code for

int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
case 2:
case 3:
case 4:
    Console.WriteLine("x");
    break;
default:
    Console.WriteLine("Default case");
    break;
}

i have multiple conditions and same result and i don't want to write all code

case when cond1 then result1
     when cond2 then result1
     when cond3 then result1
     ....
     end

any ideas ? thanks

like image 285
Zyku Avatar asked Dec 28 '22 05:12

Zyku


2 Answers

Something like this:

DECLARE @caseSwitch INT=1
SELECT
    CASE WHEN @caseSwitch IN (1,2,3,4)
    THEN 'x'
    ELSE 'Default case'
END

In a table select. It would be something like this:

DECLARE @caseSwich INT=1
SELECT
    (
       CASE WHEN @caseSwich IN (1,2,3,4)
          THEN 'x'
          ELSE 'Default case'
       END
    ) AS someColumn
FROM
    yourTable
like image 180
Arion Avatar answered Jan 09 '23 04:01

Arion


DECLARE @i INT
SET @i = 2
SELECT CASE WHEN @i IN (1,2,3,4) THEN 'Hi' ELSE 'HiHi' END AS Result
like image 34
Simon Wang Avatar answered Jan 09 '23 04:01

Simon Wang