从案例表达式向表中插入值

时间:2019-04-01 15:22:11

标签: sql

此案例表达式确定当前批准人值。每次执行此case表达式时,我都想将当前批准人值插入CURRENT_APPROVER列(所有表相同)中。您通过插入到来完成此操作吗?我在语法上遇到了麻烦。

SELECT 
    CASE 
       WHEN FORM_TYPE IN ('Form_Type1', 'Form_Type2', 'Form_Type3') 
            AND SIGNATURE_FIELD1 IS NULL 
            AND STATUS = 'Pending Approval' 
          THEN 'Signature 1 Needed'
       WHEN FORM_TYPE IN ('Form_Type1', 'Form_Type2', 'Form_Type3') 
            AND SIGNATURE_FIELD2 IS NULL 
            AND STATUS = 'Pending Approval' 
           THEN SIGNATURE_FIELD1_ASSIGNMENT
        WHEN FORM_TYPE IN ('Form_Type1', 'Form_Type2', 'Form_Type3') 
            AND SIGNATURE_FIELD3 IS NULL 
            AND STATUS = 'Pending Approval'  
           THEN SIGNATURE_FIELD2_ASSIGNMENT
        WHEN FORM_TYPE IN ('Form_Type1', 'Form_Type2', 'Form_Type3') 
             AND SIGNATURE_FIELD4 IS NULL 
             AND SIGNATURE_FIELD2 IS NOT NULL 
             AND SIGNATURE_FIELD3 IS NOT NULL 
             AND SIGNATURE_FIELD1 IS NOT NULL 
             AND STATUS = 'Pending Approval'  
            THEN 'Signature 4 Needed'
        ELSE 'Unavailable'
    END AS CURRENT_APPROVER
FROM 
    FINANCE_TABLE;

1 个答案:

答案 0 :(得分:0)

这会将CURRENT_APPROVER设置为SELECT CASE中的值为null的值(如果该列的所有行均为null,则可以删除最后一个WHERE条件)。要使正确的行更新为正确的值,您需要通过表的主键将内部SELECT查询与UPDATE查询结合起来。我以id为例,但是您需要将其替换为真正的主键

UPDATE FINANCE_TABLE f
SET CURRENT_APPROVER = (SELECT 
                        CASE 
                        WHEN FORM_TYPE IN ('Form_Type1','Form_Type2','Form_Type3') AND SIGNATURE_FIELD1 IS NULL AND STATUS = 'Pending Approval' THEN 'Signature 1 Needed'
                        WHEN FORM_TYPE IN ('Form_Type1','Form_Type2','Form_Type3') AND SIGNATURE_FIELD2 IS NULL AND STATUS = 'Pending Approval' THEN SIGNATURE_FIELD1_ASSIGNMENT
                        WHEN FORM_TYPE IN ('Form_Type1','Form_Type2','Form_Type3') AND SIGNATURE_FIELD3 IS NULL AND STATUS = 'Pending Approval'  THEN SIGNATURE_FIELD2_ASSIGNMENT
                        WHEN FORM_TYPE IN ('Form_Type1','Form_Type2','Form_Type3') AND SIGNATURE_FIELD4 IS NULL AND SIGNATURE_FIELD2 IS NOT NULL AND SIGNATURE_FIELD3 IS NOT NULL AND SIGNATURE_FIELD1 IS NOT NULL AND STATUS = 'Pending Approval'  THEN 'Signature 4 Needed'
                        ELSE 'Unavailable'
                        END AS CURRENT_APPROVER
                        FROM FINANCE_TABLE f2
                        WHERE f.id = f2.id) -- This needs to be updated

WHERE f.CURRENT_APPROVER IS NULL;

我使用this answer作为此处答案的模板