嵌套CASE ELSE END语法错误

时间:2014-05-08 18:56:50

标签: sql sql-server

有人可以告诉我为什么我在最后一个ELSE语句中收到错误的语法错误。

SELECT 
CASE WHEN PolType = 'PKG' THEN 

    CASE WHEN PkgDef & 1 = 1 THEN 'BA ' ELSE

    CASE WHEN PkgDef & 2 = 2 THEN 'BAT' ELSE

    CASE WHEN PkgDef & 4 = 4 THEN 'GS ' ELSE

    CASE WHEN PkgDef & 8 = 8 THEN 'DLR' ELSE

    'ERR' END 
ELSE 
    poltype 
END AS 'PolType'

FROM Parallel_Test.dbo.PolicyG 
WHERE rowid = (SELECT MAX(rowid) FROM Parallel_Test.dbo.policyg) - 10

3 个答案:

答案 0 :(得分:0)

不是测试,但请尝试:

SELECT CASE WHEN PolType <> 'PKG' THEN poltype
WHEN PkgDef & 1 = 1 THEN 'BA '
WHEN PkgDef & 2 = 2 THEN 'BAT'
WHEN PkgDef & 4 = 4 THEN 'GS '
WHEN PkgDef & 8 = 8 THEN 'DLR'
ELSE 'ERR'
END AS 'PolType'
FROM Parallel_Test.dbo.PolicyG 
WHERE rowid = (SELECT MAX(rowid) FROM Parallel_Test.dbo.policyg) - 10

答案 1 :(得分:0)

如果您使用的是Microsoft SQL Server,那么您可能会尝试这样做:

SELECT 
CASE 
    WHEN PolType = 'PKG' THEN
        CASE 
            WHEN PkgDef & 1 = 1 THEN 'BA ' 
            WHEN PkgDef & 2 = 2 THEN 'BAT' 
            WHEN PkgDef & 4 = 4 THEN 'GS ' 
            WHEN PkgDef & 8 = 8 THEN 'DLR' 
        ELSE 'ERR' 
        END 
    ELSE poltype 
END AS 'PolType'

FROM Parallel_Test.dbo.PolicyG 
WHERE rowid = (SELECT MAX(rowid) FROM Parallel_Test.dbo.policyg) - 10

如果我错误地解释了您的逻辑,请告诉我。

答案 2 :(得分:0)

这是你的case语句实际上正在做的事情(4层嵌套if) 我在另一个'末尾'添加了你需要更正陈述的陈述。 (我确实认为其他解决方案之一就是您正在寻找的)

    CASE 
        WHEN PkgDef & 1 = 1 THEN 'BA ' 
        ELSE CASE 
                WHEN PkgDef & 2 = 2 THEN 'BAT' 
                ELSE CASE 
                        WHEN PkgDef & 4 = 4 THEN 'GS ' 
                        ELSE CASE 
                            WHEN PkgDef & 8 = 8 THEN 'DLR' 
                            ELSE 'ERR' 
                            END 
                    end
            end

END AS 'PolType'

FROM Parallel_Test.dbo.PolicyG 
WHERE rowid = (SELECT MAX(rowid) FROM Parallel_Test.dbo.policyg) - 10