简体   繁体   中英

How to execute multiple oracle queries using single connection?

I have 3 tables in my database and their schema looks something like,

Table1 (Col1 Pk, Col2), 
Table2 (Col3 Pk, Col1 FK, Col4)
Table3 (Col5 Pk, Col3 FK, Col6)

Here the values of primary key columns is auto incremented on every insert operation. I want to insert values in the above tables. With the above scenario i cannot insert into Table3 unless i have value of Col3 (foreign key to Table2), similarly insert into Table2 won't go through unless i have value for Col1 (foreign key to Table1)

Question: How can i insert into the above tables in a single database connection ?

I can always make 3 different calls and insert values, but how can i use the value from Table1 and use it to insert into Table2, likewise value for Table2 and use it to insert into Table3 in single connection ?

I thought of writing a stored procedure but not sure how can i fetch Col1 value and use it to insert into Table2.

Pls suggest some thoughts here. An example will also help.

Thank you.

I think, you're looking for this. Just use Returning to retrieve the PK value and use the value on next insert

declare
    v_col1_id number(10) := null;
    v_col3_id number(10) := null;
begin
    insert into T1 (col2) values ('xxx') RETURNING col1 INTO v_col1_id; -- col1 - PK
    insert into T2 (col1, col4) values (v_col1_id, 'yyy') RETURNING col3 INTO v_col3_id; -- col3 - PK
    insert into T3 (col3, col6) values (v_col3_id , 'zzz'); -- col5 - PK
end;
/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM