Reputation: 1449
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
Upvotes: 4
Views: 6466
Reputation: 57033
If the set of values are small and stable then use a CASE
expression, otherwise put the values in a lookup table e.g.
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 );
Upvotes: 1
Reputation: 31239
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
Upvotes: 8
Reputation: 2943
DECLARE @i INT
SET @i = 2
SELECT CASE WHEN @i IN (1,2,3,4) THEN 'Hi' ELSE 'HiHi' END AS Result
Upvotes: 1