If you want to perform an insert into two or more tables using an INSERT ALL
and also set the primary key to a unique number for each table based
on a sequence, then the following is a method that could be used.
For example;
Create some test tables first;
create table t1 (a number primary key, b number);
create table t2 (a number primary key, b number);
Create the sequence next.
The trick is to create the sequence with an increment value equal to
the number of tables being inserted into. So if you have three tables
then the increment value would be three. In the example we have two tables
so the increment value is 2.
create sequence test_seq increment by 2 minvalue 0;
Now for the test;
insert all
when 1 = 1 then
into t1 (a, b) values (test_seq.nextval, 1)
when 1 = 1 then
into t2 (a, b) values (test_seq.nextval - 1, 1)
select 1, 1 from dual;
SQL> select * from t1
2 union all
3 select * from t2
4 order by 1;
A B
---------- ----------
3 1
4 1
One might want to wrap the insert in a procedure, since although the
trick works in versions 10g and 11g, future versions might not output
the same results. The INSERT ALL within the procedure would refer to
a number (which would be passed as a parameter) instead of the
sequence.
For example;
create or replace procedure p_Test (p_Number in number) as
begin
insert all
when 1 = 1 then
into t1 (a, b) values (p_Number, 1)
when 1 = 1 then
into t2 (a, b) values (p_Number - 1, 1)
select 1, 1 from dual;
end p_Test;
/
Now test using the procedure;
SQL> exec p_Test(test_seq.nextval);
PL/SQL procedure successfully completed.
SQL> select * from t1
2 union all
3 select * from t2
4 order by 1;
A B
---------- ----------
3 1
4 1
5 1
6 1
I use this blog as a dumping ground for various scripts as well as solutions to Maths problems.
Labels
- Alter (2)
- Analytic functions (2)
- AQ (2)
- AWR (4)
- Collections (2)
- Connect By (2)
- Constraints (7)
- Date/Time calculations (3)
- Dynamic SQL (4)
- Explain Plan (1)
- Formatting (3)
- Functions (1)
- Generating Functions (1)
- Indexes (7)
- Insert (3)
- JMS (3)
- Joins (4)
- LOB (3)
- locking (5)
- Partitions (3)
- Performance (10)
- Security (1)
- SQL Plus (3)
- Tabibitosan (1)
- Triggers (1)
- Views (1)
- XML (4)
Script categories
- Performance (10)
- Constraints (7)
- Indexes (7)
- locking (5)
- AWR (4)
- Dynamic SQL (4)
- Joins (4)
- XML (4)
- Date/Time calculations (3)
- Formatting (3)
- Insert (3)
- JMS (3)
- LOB (3)
- Partitions (3)
- SQL Plus (3)
- AQ (2)
- Analytic functions (2)
- Collections (2)
- Connect By (2)
- Explain Plan (1)
- Functions (1)
- Security (1)
- Triggers (1)
- Views (1)
Wednesday, 2 November 2011
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment