Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, ayush.

Asked: September 23, 2017 - 1:41 pm UTC

Last updated: September 24, 2017 - 2:09 pm UTC

Version: 11g

Viewed 1000+ times

You Asked

Hi Tom,

i need to write a plsql program,
Suppose there are 10 sup tables with different columns in each table and 1 target table which have columns same as combined all source columns. i need to write a procedure which will extracts the data from source tables and dump in target table. the catch is in future if more source tables get added which will definitely add some new columns in target table... code should not be changed.

could you please help me on that.

with LiveSQL Test Case:

and Connor said...

Sounds like just a series of merges to me.

SQL> create table t1 ( pk int, c1 int, c2 int );

Table created.

SQL> create table t2 ( pk int, c3 int, c4 int );

Table created.

SQL>
SQL> insert into t1 select rownum, rownum, rownum from dual connect by level <= 10;

10 rows created.

SQL> insert into t2 select rownum, rownum, rownum from dual connect by level <= 10;

10 rows created.

SQL>
SQL> create table target ( pk int, c1 int, c2 int, c3 int, c4 int );

Table created.

SQL>
SQL> merge into target
  2  using ( select * from t1 ) t1
  3  on ( target.pk = t1.pk )
  4  when matched
  5  then update
  6    set target.c1 = t1.c1,
  7        target.c2 = t1.c2
  8  when not matched
  9  then insert ( target.pk, target.c1, target.c2 )
 10  values ( t1.pk, t1.c1, t1.c2 );

10 rows merged.

SQL>
SQL>
SQL> merge into target
  2  using ( select * from t2 ) t2
  3  on ( target.pk = t2.pk )
  4  when matched
  5  then update
  6    set target.c3 = t2.c3,
  7        target.c4 = t2.c4
  8  when not matched
  9  then insert ( target.pk, target.c3, target.c4 )
 10  values ( t2.pk, t2.c3, t2.c4 );

10 rows merged.

SQL>
SQL> select * from target order by 1;

        PK         C1         C2         C3         C4
---------- ---------- ---------- ---------- ----------
         1          1          1          1          1
         2          2          2          2          2
         3          3          3          3          3
         4          4          4          4          4
         5          5          5          5          5
         6          6          6          6          6
         7          7          7          7          7
         8          8          8          8          8
         9          9          9          9          9
        10         10         10         10         10

10 rows selected.



You could query the data dictionary to dynamically generate those merge commands as tables are added.

Is this answer out of date? If it is, please let us know via a Comment

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library