SQL 2005我可以在case语句中使用关键字

时间:2011-10-07 13:08:35

标签: sql sql-server-2005 tsql

我需要一个允许部分匹配的case语句。我收到语法错误,但我想知道是否有类似的东西是可能的。如果没有,我的辅助解决方案是重写为光标... 例如:

SELECT CASE ColumnName
           WHEN 'value1' THEN 'answer1'
           WHEN 'value2' THEN 'answer2'
           WHEN LIKE '%TEST%' THEN 'answer3'
       END AS Answer
FROM TableName

5 个答案:

答案 0 :(得分:30)

试试这个

SELECT CASE 
           WHEN ColumnName = 'value1' THEN 'answer1'
           WHEN ColumnName = 'value2' THEN 'answer2'
           WHEN ColumnName LIKE '%TEST%' THEN 'answer3'
       END AS Answer
FROM TableName

例如你可以运行

SELECT name,CASE 
           WHEN Name = 'sysobjects' THEN 'answer1'
           WHEN Name = 'syscols' THEN 'answer2'
           WHEN Name LIKE '%p%' THEN 'answer3'
           ELSE 'unknown'
       END AS Answer
FROM sysobjects

答案 1 :(得分:7)

需要使用略有不同的CASE语法:

SELECT CASE WHEN ColumnName LIKE 'value1' THEN 'answer1'
            WHEN ColumnName LIKE 'value2' THEN 'answer2'
            WHEN ColumnName LIKE '%TEST%' THEN 'answer3'
ELSE 'not like any of them' END [Answer]
FROM TableName

答案 2 :(得分:3)

或者,您可以嵌套CASE条件和CASE WHEN值子句,如下所示:

SELECT CASE ColumnName
           WHEN 'value1' THEN 'answer1'
           WHEN 'value2' THEN 'answer2'
           ELSE CASE WHEN ColumnName LIKE '%TEST%' THEN 'answer3' END
       END AS Answer
FROM TableName

答案 3 :(得分:2)

您使用的是“简单CASE表达式”,但您应该使用“已搜索的CASE表达式”。有关示例,请参阅the documentation

答案 4 :(得分:0)

在sql ORACLE 10中

SELECT 
    CASE WHEN instr(ColumnName, 'value1')>0 THEN 'answer1'
       WHEN instr(ColumnName,'value2')>0 THEN 'answer2'
       WHEN instr(ColumnName,'TEST')>0 THEN 'answer3'
       ELSE 'not like any of them' 
    END
FROM TableName