Link to home
Start Free TrialLog in
Avatar of manikandanra
manikandanra

asked on

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.

Like,

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.
ASKER CERTIFIED SOLUTION
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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:
declare
v_sql varchar2(4000);
v_tgt varchar2(30);
begin
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;
end;
/
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.