Du kan bruge returning into
klausul i insert
sætning for at returnere users_id
værdi efter en ny post er blevet indsat i table1
. Du kan også bruge user_seq.currval
for at få den aktuelle værdi af sekvensen. Her er et eksempel (I dette eksempel er en simpel lagret procedure blevet implementeret for at demonstrere brugen af insert into
klausul. Du kan implementere en lignende lagret procedure i henhold til dine krav):
SQL> create table Tb_table_1(
2 user_id number primary key,
3 field_1 number
4 );
Table created
SQL>
SQL> create table Tb_table_2(
2 user_id number references tb_table_1(user_id),
3 name1 varchar2(17)
4 );
Table created
SQL> create sequence user_seq
2 start with 1
3 increment by 1
4 nomaxvalue;
Sequence created
SQL>
SQL> create trigger user_trigger
2 before insert on tb_table_1
3 for each row
4 begin
5 select user_seq.nextval into :new.user_id from dual;
6 end;
7 /
Trigger created
SQL> create or replace procedure Insert_Record
2 is
3 l_cur_id number;
4 begin
5 insert into Tb_table_1(Field_1)
6 values(123)
7 returning user_id into l_cur_id; -- store user_id of the new inserted record
8 for i in 1..5 -- in a local variable for later use
9 loop
10 insert into tb_table_2(user_id, name1) -- insert a bunch of sample data into table2 using previously stored user_id.
11 values(l_cur_id, dbms_random.string('l', 7));
12 end loop
13 commit;
14 end;
15 /
Procedure created
SQL> select * from tb_table_1;
USER_ID FIELD_1
---------- ----------
SQL> select * from tb_table_2;
USER_ID NAME1
---------- -----------------
SQL> exec insert_record;
PL/SQL procedure successfully completed
SQL> select * from tb_table_1
2 ;
USER_ID FIELD_1
---------- ----------
1 123
SQL> select * from tb_table_2;
USER_ID NAME1
---------- -----------------
1 jzsdbna
1 ozbibgs
1 btxrxcm
1 hxwwpzc
1 sdjbwzi
SQL>
I Oracle 11g og fremefter kan du direkte tildele sekvensværdi til en variabel:
:new.users_id := user_seq.nextval;