If you have a pair of tables with a numeric primary key and a parent-child relationship, what's the best way of copying records in these tables, given that if you do it as two separate inserts, the key for the parent will have changed?
Perhaps best explained with an example. Say you had the following table structure:
CREATE TABLE APARENT (
APARENT_CODE NUMBER, -- primary key
AVALUE1 NUMBER,
AVALUE2 NUMBER
);
CREATE TABLE ACHILD (
ACHILD_CODE NUMBER, -- primary key
APARENT_CODE NUMBER, -- foreign key
AVALUE3 NUMBER
);
The values in APARENT
are parent records. They may have many records in the ACHILD
table, linked back to them by the APARENT_CODE
field.
What's the best way of copying a record (which includes a single parent and perhaps multiple child records)? My confusion arises because when you insert the duplicate records into the parent table you necessarily have to change the primary key value (in this case through a sequence) so when you insert the child records, how do you know which foreign key value to link them to?
Edit: Sorry, editing in case this isn't clear: The first insert is copying multiple records, so CURRVAL cannot be used in the second insert.
At the moment I'm using this code:
CREATE TABLE TMP_CODES (
OLD_APARENT_CODE NUMBER,
NEW_APARENT_CODE NUMBER
);
INSERT INTO TMP_CODES
SELECT APARENT_CODE,
SQ_APARENT.NEXTVAL -- gets new sequence value
FROM APARENT
WHERE AVALUE1 = 10;
INSERT INTO APARENT
SELECT C.NEW_APARENT_CODE, -- the copied parent records get a new sequence value
A.VALUE1,
A.VALUE2
FROM APARENT A,
TMP_CODES C
WHERE A.AVALUE1 = 10
AND C.OLD_APARENT_CODE = A.APARENT_CODE;
INSERT INTO ACHILD
SELECT SQ_ACHILD.NEXTVAL, -- a new sequence value for the primary key
C.NEW_APARENT_CODE, -- this inserts the correct link value
A.VALUE3
FROM ACHILD A,
TMP_CODES C
WHERE C.OLD_APARENT_CODE = A.APARENT_CODE;
I'm just wondering if there's a more efficient way of doing it, rather than expressing all the codes into a temporary table first.
I'm using Oracle 10. Thanks for any help.