T-SQL CASE multiple Conditions are the same Result

I need in SQL 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 several conditions and one result and I do not want to write all the code

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

any ideas? thanks

+4
source share
3 answers

Something like that:

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

In the table, select. It will 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 
+8
source
 DECLARE @i INT SET @i = 2 SELECT CASE WHEN @i IN (1,2,3,4) THEN 'Hi' ELSE 'HiHi' END AS Result 
+1
source

If the set of values ​​is small and stable, then use the CASE expression, otherwise put the values ​​in the lookup table, for example.

 SELECT T.*, L.lookup_value AS result FROM T JOIN LookupTable ON T.lookup_key = L.lookup_key UNION SELECT T.*, 'Default case' AS result FROM T WHERE lookup_key NOT IN ( SELECT lookup_key FROM LookupTable ); 
+1
source

Source: https://habr.com/ru/post/1397744/


All Articles