使用多个条件和多个行进行更新

时间:2019-03-05 10:13:30

标签: sql db2

我希望能够使用一个UPDATE语句来更新表,但是要在其中包含各种条件。以下代码包含一个表test_table,其中包含main_id,其中main_id可以具有product_case id和customer_case id。我希望能够检查表CASETABLE,并且如果与main_id相关联的是'PC'情况还是'CC'情况,然后更新相应的字段。

UPDATE 
    test_table tt
SET 
    tt.product_case = CASE WHEN ct.TYPE = 'PC' THEN ct.ID ELSE tt_.product_case END,
    tt.customer_case = CASE WHEN ct.TYPE = 'CC' THEN ct.ID ELSE tt.customer_case END
FROM 
    CASETABLE ct 
WHERE 
    ct.STATUS = 'ACTIVE'
    AND ct.MAINRECORD = tt.main_id

显然,如果主WHERE返回2行,则此方法不起作用,因为每种情况将尝试设置正确的值,然后再次设置其原始值,从而导致SQL错误21506(尝试为同一行设置多个)。我怎么能不只使用两个单独的UPDATE语句呢?

3 个答案:

答案 0 :(得分:2)

请尝试这个

UPDATE 
   tt
SET 
    tt.product_case = CASE WHEN ct.TYPE = 'PC' THEN ct.ID ELSE tt_.product_case END,
    tt.customer_case = CASE WHEN ct.TYPE = 'CC' THEN ct.ID ELSE tt.customer_case END
FROM 
    test_table tt
    INNER JOIN CASETABLE ct 
    ON ct.MAINRECORD = tt.main_id
WHERE 
    ct.STATUS = 'ACTIVE'

答案 1 :(得分:0)

您可以在下面尝试-

   UPDATE test_table tt
    SET tt.product_case = 
        (SELECT CASE WHEN ct.TYPE = 'PC' THEN ct.ID ELSE tt_.product_case END
        FROM CASETABLE ct WHERE ct.MAINRECORD = tt.main_id),
    tt.customer_case=(SELECT CASE WHEN ct.TYPE = 'CC' THEN ct.ID ELSE tt_.product_case END
        FROM CASETABLE ct WHERE ct.MAINRECORD = tt.main_id)
    WHERE EXISTS(
        SELECT 1
        FROM CASETABLE ct
        WHERE ct.MAINRECORD = tt.main_id and STATUS = 'ACTIVE')

答案 2 :(得分:0)

使用具有条件聚合的子查询:

UPDATE test_table tt
    SET tt.product_case = COALESCE(ct.pc, tt.product_case), 
        tt.customer_case = COALESCE(ct.cc, tt.customer_case)
    FROM (SELECT ct.MAINRECORD,
                 MAX(CASE WHEN ct.TYPE = 'PC' THEN ct.ID END) as pc,
                 MAX(CASE WHEN ct.TYPE = 'CC' THEN ct.ID END) as cc
          FROM CASETABLE ct 
          WHERE ct.STATUS = 'ACTIVE'
          GROUP BY ct.MAINRECORD
         ) ct
    WHERE ct.MAINRECORD = tt.main_id ND
          (ct.pc is not null or ct.cc is not null);