Oracle Update Join

前端 未结 2 1566
一整个雨季
一整个雨季 2021-01-26 09:54

I would like to update a table by referencing values within it\'s own row and also it\'s parent record in the same table.

I have a table called import, and it needs to u

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-26 10:12

    The problem I see is you're wanting preform 2 updates at the same time. Effectively, what you have are two tables c and p with a hierarchical relation. I don't know of a sql only way in oracle to update 2 tables at once. There are some tricks you could do with views and possibly some really fancy SQL.

    However, fancy is not always the best solution.

    I would recommend using a little pl/sql such as

    BEGIN
      FOR v_rec IN (SELECT c.chain_id AS c_chain_id,
                         c.status AS c_status,
                         c.action AS c_action,
                         p.chain_id AS p_chain_id,
                         p.status AS p_status,
                         c.dissemination_id AS c_dissemination_id,
                         p.dissemination_id AS p_dissemination_id
                    FROM import c
                    JOIN import p ON c.original_dissemination_id = p.dissemination_id
                   WHERE c.chain_id = 0
                     AND p.chain_id <> 0) LOOP
    
        UPDATE import
           SET chain_id = v_rec.p_chain_id,
               status = decode(v_rec.c_action, 3, 1, status)
         WHERE dissemination_id = v_rec.c_dissemination_id;
    
        UPDATE import
           SET chain_id = 0
         WHERE dissemination_id = v_rec.p_dissemination_id;
    
        commit;
    
      END LOOP;
    
    END;
    /
    

    This should loop through all the records as you defined in your query above (I added what I'm assuming are the pk and fk columns to the output.) This will do the 2 updates and the decode will handle the action/status part.

    You'll of course, want to test this and put some exception handling in as needed.

提交回复
热议问题