这个语法对于计算列有什么问题?

时间:2017-04-30 22:04:46

标签: sql sql-server

ALTER TABLE table_1
ADD [calc_column]  AS
 (
        CASE 
        WHEN ([payment_1] IS NULL   
            AND [payment_2] IS NULL 
            AND [payment_3] IS NULL   
            AND [payment_4] IS NULL 
            AND [payment_5] IS NULL 
            AND [payment_6] IS NULL)  
         THEN NULL 
         ELSE (COALESCE([payment_1],(0)) + COALESCE([payment_2],(0)) +
           CASE
           WHEN (COALESCE([payment_3],(0)) + COALESCE([payment_7],(0)) + COALESCE([payment_4],(0)) > COALESCE([payment_5],(0)))
           THEN (COALESCE([payment_1],(0)) + COALESCE([payment_4],(0)) + COALESCE([payment_3],(0)))
           ELSE (COALESCE([payment_8],(0)))  END) AS DECIMAL(13,2)

1 个答案:

答案 0 :(得分:3)

有多个错误,主要是由于括号不平衡而导致end缺少cases。此外,您不需要指定类型。

所以,我认为这样可行:

ALTER TABLE table_1
   ADD [calc_column] AS (CASE WHEN [payment_1] IS NULL AND  
                                   [payment_2] IS NULL AND
                                   [payment_3] IS NULL AND
                                   [payment_4] IS NULL AND
                                   [payment_5] IS NULL AND
                                   [payment_6] IS NULL
                              THEN NULL 
                              ELSE COALESCE([payment_1], 0) + COALESCE([payment_2], 0) +
                                    (CASE WHEN COALESCE([payment_3], 0) + COALESCE([payment_7], 0) + COALESCE([payment_4], 0) > COALESCE([payment_5], 0)
                                          THEN COALESCE([payment_1], 0) + COALESCE([payment_4], 0) + COALESCE([payment_3], 0)
                                          ELSE COALESCE([payment_8], 0) 
                                     END)
                         END);