How to insert an n:m-relationship with technical primary keys generated by a sequence?
- by bitschnau
Let's say I have two tables with several fields and in every table there is a primary key which is a technical id generated by a database sequence:
table1 table2
------------- -------------
field11 <pk> field21 <pk>
field12 field22
field11 and field21 are generated by sequences.
Also there is a n:m-relationship between table1 und table2, designed in table3:
table3
-------------
field11 <fk>
field21 <fk>
The ids in table1 und table2 are generated during the insert statement:
INSERT INTO table1 VALUES (table1_seq1.NEXTVAL, ...
INSERT INTO table2 VALUES (table2_seq1.NEXTVAL, ...
Therefore I don't know the primary key of the added row in the data-access-layer of my program, because the generation of the pk happens completely in the database.
What's the best practice to update table3 now? How can I gain access to the primary key of the rows I just inserted?