Hi,
Thanks for the feedback. I am told that by using a function to return the sequence instead of directly accessing the sequence exploits PL/SQL's optimization process. However would you consider that "unsafe"?
The reason I am asking is that I was trying to resolve an issue with efficiently creating a copy of master/detail record.
So setting up just some basic data:
Create Sequence xxmaster_s;
Create Table xxmaster
As
Select xxmaster_s.nextval id, 'Dummy' || To_char (Level, 'fm00') val
From Dual
Connect By Level <= 10;
Create Table xxdetail
As
Select Mod(Level,10) + 1 master_id, 'Dummy Detail' || To_char (Round(Dbms_Random.Value(1,Level)), 'fm00') val_dtl
From Dual Connect By Level <= 100;
I now want to copy those master records 1-10 and their corresponding detail records, but assign them new sequences. So a "loops" way of doing this would be:
Declare
l_new_id xxmaster.id%Type;
Begin
For i In (Select id, val From xxmaster) Loop
Insert into xxmaster(id, val) Values (xxmaster_s.nextval,i.val)
Returning id Into l_new_id;
Insert Into xxdetail(master_id, val_dtl)
Select l_new_id, d.val_dtl
From xxdetail d
Where d.master_id = i.id;
End Loop;
End;
But I find it somewhat inefficient - especially if we are considering large volumes of data in xxmaster because we're looping through and inserting one record at a time, then executing the insert of detail records for each.
November 29, 2016 - 5:41 pm UTC
Yes, the looped method will be inefficient!
A better way would be something like:
- Add a column to the master orig_id
- Insert the rows to copy, loading the original id into the new column
- You can then find the detail rows to load by joining this table to the orig_id column on the master table