更新不使用案例...当......其他

时间:2017-12-29 21:33:22

标签: sql-server tsql

这看起来应该很简单,当我做一个简单的选择时,一切正常,但是当我尝试运行更新时,我收到一条错误,上面写着“CASE附近的语法不正确”。

Update    TBL_FBNK_CURRENCY_HIST 
SET       CURRENCY_FBNK = CURRENCY.Currency_Code,
          CURRENCY_ASOFDATE = CURRENCY.ASOFDATE,
          CURRENCY_MID_REVAL_RATE = CURRENCY.MID_REVAL_RATE,
          ORIGINAL_AMOUNT = MM_HIST.PRINCIPAL
          REPORTABLE_AMOUNT = REVAL_BALANCE
                CASE WHEN CURRENCY.ID IN('AUD','EUR','GBP','NZD','XAG','XAU','XPD','XPT') 
                    THEN (MM_HIST.PRINCIPAL * CURRENCY.Mid_Reval_Rate)
                    ELSE (MM_HIST.PRINCIPAL / CURRENCY.Mid_Reval_Rate) END AS REVAL_BALANCE
From      TBL_FBNK_CURRENCY_HIST AS CURRENCY INNER JOIN JOIN TBL_MULTI_MM_HIST AS MM_HIST 
          ON CURRENCY.Currency_Code = MM_HIST.Currency
          AND CURRENCY.ASOFDATE = MM_HIST.ASOFDATE

这里到底有什么不对?

2 个答案:

答案 0 :(得分:3)

您错过了MM_HIST.PRINCIPALREPORTABLE_AMOUNT之间的昏迷,以及REVAL_BALANCECASE之间的另一次昏迷。此外,您只是使用CASE语句返回一个值,但您没有将其分配给任何内容。

假设您希望将CASE的结果分配给REPORTABLE_AMOUNT

的字段名称
Update    TBL_FBNK_CURRENCY_HIST 
SET       CURRENCY_FBNK = CURRENCY.Currency_Code,
          CURRENCY_ASOFDATE = CURRENCY.ASOFDATE,
          CURRENCY_MID_REVAL_RATE = CURRENCY.MID_REVAL_RATE,
          ORIGINAL_AMOUNT = MM_HIST.PRINCIPAL,
          REPORTABLE_AMOUNT = CASE WHEN CURRENCY.ID IN('AUD','EUR','GBP','NZD','XAG','XAU','XPD','XPT') 
                THEN (MM_HIST.PRINCIPAL * CURRENCY.Mid_Reval_Rate)
                ELSE (MM_HIST.PRINCIPAL / CURRENCY.Mid_Reval_Rate) END
From      TBL_FBNK_CURRENCY_HIST AS CURRENCY INNER JOIN JOIN TBL_MULTI_MM_HIST AS MM_HIST 
          ON CURRENCY.Currency_Code = MM_HIST.Currency
          AND CURRENCY.ASOFDATE = MM_HIST.ASOFDATE

答案 1 :(得分:1)

整个CASE...END形成一个表达式。您的错误是您将别名REVAL_BALANCE分配给CASE表达式的结果,这在select中有意义但在更新中没有意义。

使用更新分配,如下所示:

REPORTABLE_AMOUNT = CASE WHEN CURRENCY.ID IN('AUD','EUR','GBP','NZD','XAG','XAU','XPD','XPT') 
                THEN (MM_HIST.PRINCIPAL * CURRENCY.Mid_Reval_Rate)
                ELSE (MM_HIST.PRINCIPAL / CURRENCY.Mid_Reval_Rate) END

或者您是否需要将REVAL_BALANCE与货币转换率相乘?在这种情况下,您只是忘记输入乘法运算符(*)。这可能是:

UPDATE TBL_FBNK_CURRENCY_HIST SET       
    CURRENCY_FBNK = CURRENCY.Currency_Code,
    CURRENCY_ASOFDATE = CURRENCY.ASOFDATE,
    CURRENCY_MID_REVAL_RATE = CURRENCY.MID_REVAL_RATE,
    ORIGINAL_AMOUNT = MM_HIST.PRINCIPAL,
    REPORTABLE_AMOUNT = REVAL_BALANCE * CASE WHEN 
        CURRENCY.ID IN('AUD','EUR','GBP','NZD','XAG','XAU','XPD','XPT') 
        THEN (MM_HIST.PRINCIPAL * CURRENCY.Mid_Reval_Rate)
        ELSE (MM_HIST.PRINCIPAL / CURRENCY.Mid_Reval_Rate) END
From TBL_FBNK_CURRENCY_HIST AS CURRENCY 
INNER JOIN JOIN TBL_MULTI_MM_HIST AS MM_HIST ON CURRENCY.Currency_Code = MM_HIST.Currency AND CURRENCY.ASOFDATE = MM_HIST.ASOFDATE