Dynamic Select Statement

I need to write a dynamic Select statement to copy data from all the tables in source database to target db tables.


INSERT INTO SRC_TAB_1 (col1, col 2, col3) SELECT col1, col2, col 3 FROM TRG_TAB_1;
INSERT INTO SRC_TAB_2 (col1, col 2, col3) SELECT col1, col2, col 3 FROM TRG_TAB_2;

I have few additional columns in all the target tables which also needs to be populated with default values.

E.g. BATCH_ID = 100, DATE = SYSDATE etc.

Please can anyone advise how to write a SELECT query to copy from 1 table to another dynamically along with populating additional columns as described above.
Who is Participating?
slightwv (䄆 Netminder) Commented:
Just make them literals?

INSERT INTO SRC_TAB_1 (col1, col 2, col3, batch_col, date_col) SELECT col1, col2, col 3, 100, sysdate FROM TRG_TAB_1;

To make it 'dynamic', you can use variables.  How you create variables depends on the tool you are using.

In sqlplus it is:
variable batch_id number
exec :batch_id := 100;

insert ... select :batch_id, ...
Without being able to see the table structures of both the source and target tables, it's a little difficult to determine how the dynamic sql should be constructed. Also, would this include tables from a single schema or selected schemas or all schemas? Would all of the target tables have the same default values with the same column names? A simple example of dynamic sql that copies data from some tables to other tables might take the following form:
v_sql varchar2(4000);
v_tgt varchar2(30);
for t in (select table_name from user_tables where table_name in (src_tab1, src_tab2) loop
v_tgt := replace(t.table_name,'src','tgt');
v_sql := 'insert into '||v_tgt||' select a.*, 100 as batch_id, sysdate as sdate from '||t.table_name||' a';
execute immediate v_sql;
end loop;
The above would require a lot of unlikely assumptions such as the table structures (i.e. column order) and names would have to be identical except for the src and tgt reference and for the two default target columns which would have to be at the end. I think we need a lot more detail before we develop a solution for your case.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.