I have a one-to-many relationship between two tables:
table1:
NUMBER users_id (primary key)
field2
field3
...
table2:
NUMBER users_id (foreign key)
VARCHAR2 name
...
...
and when I INSERT into table1, I want to auto increment (sequence?) users_id and insert a number of records into table2 all with the same users_id so I end up with
table1:
1,val1,val2
table2:
1,barry,...
1,bob,...
1,james,...
I think I need a trigger with a sequence to auto-increment users_id in table1 and create the rows in table2.
It might not be relevant but I’m doing this from a PHP script.
UPDATE
So far I have a sequence and a trigger set up so I can INSERT into table1 and have the users_id field auto-increment:
create sequence user_seq
start with 1
increment by 1
nomaxvalue;
create trigger user_trigger
before insert on table1
for each row
begin
select user_seq.nextval into :new.users_id from dual;
end;
so now I just need to automatically insert into the second table.
Many thanks.
You can use
returning intoclause of theinsertstatement to returnusers_idvalue after a new record has been inserted intotable1. Also you can useuser_seq.currvalto get the current value of the sequence. Here is an example (In this example a simple stored procedure has been implemented to demonstrate the usage ofinsert intoclause. You can implement a similar stored procedure according to your requirements):In Oracle 11g onward you can directly assign sequence value to a variable: