DECLARE
cursor curs is select * from starting;
appleId number;
bananaId number;
BEGIN
for foo in curs
LOOP
insert into apple (id, weight)
values(1,1)
returning id into appleId;
insert into banana(id,weight)
values(1,3)
returning id into bananaId;
insert into apple_banana_lookup
values(1,appleId,bananaId);
END LOOP;
COMMIT;
END;
The above code results in a foreign key constraint violation. Claiming that the ID field in Apple does not yet exist. My question is how do I make this code function above and have the apple_banana_lookup table successfully persist the keys referenced in appleId and bananaId . As an added I want to avoid having to commit after every insert into apple and banana on account of there will be ~200 millions records in a given cursor.
UPDATE
Schema declaration:
create table apple
(
id number(20,0) not null,
weight number (20,0)
);
create table banana
(
id number(20,0) not null,
weight number(20,0)
) ;
create table apple_banana_lookup
(
id number(20,0) not null,
appleId number(20,0) not null,
bananaId number(20,0) not null
CONSTRAINT "apple_fk" foreign key ("appleId")
REFERENCES "apple" ("id"),
CONSTRAINT "banana_fk" foreign key ("bananaId")
REFERENCES "banana" ("id"),
);
ERROR MESSAGE:
ORA-02291: integrity constraint
parent key not found
Something appears to be left out of your explanation– your code appears to work correctly when the tables are created correctly
I’m assuming that this is how the
apple,banana, andapple_banana_lookuptables are defined (note that since you don’t specify the column list on your insert intoapple_banana_lookup, I’m assuming that the columns in the table are ordered as your PL/SQL block seems to expect them to be).Just to avoid making any changes to your code, I created a
startingtable with 1 rowNow I run your code exactly as you posted it. No errors are generated and one row is inserted into each table.