开发者

catching created IDs in cursor loop

I have the following cursor (something like it anyways) that I am using to copy entries for a table that is part of a many to many relationship. I need the new IDs that are generated during the INSER开发者_如何学GoT INTO B statement to update a junction table with.

DECLARE

BEGIN
   FOR rec IN (SELECT id
                 FROM A
                WHERE group_id = 7)
   LOOP
      INSERT INTO B (b_id, thing2, ...stuff...);

      INSERT INTO C (rec.id, /* new ID generated by previous insert statement */
      COMMIT;
   END LOOP;
END;
/

How do I capture the b_id value after the insert to use in the second INSERT statement?


Use the RETURNING clause:

DECLARE

  v_bid B.b_id%TYPE;

BEGIN
   FOR rec IN (SELECT id
                 FROM A
                WHERE group_id = 7)
   LOOP
     INSERT INTO B (b_id, thing2, ...stuff...) RETURNING b_id INTO v_bid;

     INSERT INTO C (rec.id, /* new ID generated by previous insert statement */
     COMMIT;
   END LOOP;
END;

That said, it's possible this operation could be performed without the use of a cursor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜