Jeffrey Clarke Jeffrey Clarke - 1 year ago 53
SQL Question

Nested CASE ELSE END Syntax Error

Can someone tell me why I'm getting an Incorrect Syntax error at the last ELSE statement.

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

Answer Source

If you are using Microsoft SQL Server then you might be trying to do this:

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

Let me know if I have interpreted your intended logic wrongly.