SQL Server Case Expression无法使用第二个条件

时间:2017-10-12 10:54:03

标签: sql sql-server case

我有sql server case表达式,当它到达这一行时似乎不起作用:

 WHEN cl.Product_Type = 'PerformanceSwap' and 
 cl.Underlying_Product_Code_IndexType IS NULL THEN

完整的代码块是:

CASE
WHEN prod_map.Product_ID1 = 'CR' AND prod_map.Product_Type <> 
'PerformanceSwap' THEN  
--(mandatory for transactions where asset_class = CR)
   CASE 
     WHEN cl.AB_Payment_Frequency = 'Monthly' THEN 'MNTH'
     WHEN cl.AB_Payment_Frequency = 'Quarterly' THEN 'QURT'
     WHEN cl.AB_Payment_Frequency = 'Yearly' THEN 'YEAR'

         WHEN cl.Product_Type = 'PerformanceSwap' and 
         cl.Underlying_Product_Code_IndexType IS NULL THEN
            CASE
            WHEN cl.AB_Finance_Payment_Frequency = 'MNTH' THEN 'MNTH'
            WHEN cl.AB_Finance_Payment_Frequency = 'SW' THEN 'MIAN'
            WHEN cl.AB_Finance_Payment_Frequency = 'QTR' THEN 'QURT'
            WHEN cl.AB_Finance_Payment_Frequency = 'PA' THEN 'YEAR'
            WHEN cl.AB_Finance_Payment_Frequency = 'ZC' THEN 'YEAR'
ELSE ''
END
END
END,

我需要在其中做另一个案例表达吗?或其他东西,以便它可以提高AB_Finance_Payment_Frequency值。

1 个答案:

答案 0 :(得分:2)

我猜您正在过度使用case 表达式

两个&#34;外部&#34;的逻辑WHEN比较不兼容 - 只需查看Product_Type逻辑即可。第二个应该遵循第一个而不是嵌套。

这可能是你想要的:

(CASE WHEN prod_map.Product_ID1 = 'CR' AND prod_map.Product_Type <> 'PerformanceSwap'
      THEN  --(mandatory for transactions where asset_class = CR)
            (CASE WHEN cl.AB_Payment_Frequency = 'Monthly' THEN 'MNTH'
                  WHEN cl.AB_Payment_Frequency = 'Quarterly' THEN 'QURT'
                  WHEN cl.AB_Payment_Frequency = 'Yearly' THEN 'YEAR'
             END)
      WHEN cl.Product_Type = 'PerformanceSwap' and cl.Underlying_Product_Code_IndexType IS NULL
      THEN (CASE WHEN cl.AB_Finance_Payment_Frequency = 'MNTH' THEN 'MNTH'
                 WHEN cl.AB_Finance_Payment_Frequency = 'SW' THEN 'MIAN'
                 WHEN cl.AB_Finance_Payment_Frequency = 'QTR' THEN 'QURT'
                 WHEN cl.AB_Finance_Payment_Frequency = 'PA' THEN 'YEAR'
                 WHEN cl.AB_Finance_Payment_Frequency = 'ZC' THEN 'YEAR'
                 ELSE ''
            END)
 END)

但是,我注意到您仍然只有一个ELSE子句。我怀疑你需要的逻辑可能有点不同。你应该将它映射出来然后实现它。

我还鼓励你仔细缩进代码,这样你就可以轻松地遵循逻辑。