T-SQL CASE多个条件相同的结果

时间:2012-02-22 08:18:50

标签: sql sql-server tsql

我需要在SQL中使用

的等效C#代码
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
case 2:
case 3:
case 4:
    Console.WriteLine("x");
    break;
default:
    Console.WriteLine("Default case");
    break;
}

我有多个条件和相同的结果 我不想写所有代码

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

任何想法? 感谢

3 个答案:

答案 0 :(得分:8)

这样的事情:

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

在表格中选择。它会是这样的:

DECLARE @caseSwich INT=1
SELECT
    (
       CASE WHEN @caseSwich IN (1,2,3,4)
          THEN 'x'
          ELSE 'Default case'
       END
    ) AS someColumn
FROM
    yourTable

答案 1 :(得分:1)

DECLARE @i INT
SET @i = 2
SELECT CASE WHEN @i IN (1,2,3,4) THEN 'Hi' ELSE 'HiHi' END AS Result

答案 2 :(得分:1)

如果值集很小且稳定,则使用CASE表达式,否则将值放在查找表中,例如

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 );