Question

I am trying to write a data migration pl/sql script to transfer some of the data in one schema to a different schema on another server. The second database started as a subset of the original database, but we have modified the schema. So I can't just use the following for each table:

Insert into DB2.table_name select * from DB1.table_name2; 

I have tried doing a search for sample scripts that show how to do this, but couldn't find anything.

Was it helpful?

Solution

You can create a database link.

Then, if you're trying to migrate from db1 to db2:

Insert into table_name (f1, f2, etc) select (f1, f2, etc) from table_name2@DB2;

The select can be as complex or simple as needed.

OTHER TIPS

If the columns are different between DB1.table_name and DB2.table_name then you're going to have to specify a column list in the insert statement. Unfortunately, there's not really a "magic bullet" here.

With that said, to speed up the process you could write some PL/SQL to generate the insert statements, and then you could fix those by hand. Here's a sample PL/SQL code to do this. In this example, l_src_table would be your source table and l_target_table would be your target table. Obviously, you'll still have to manually fix the SQL statement this code generates, but this will at least generate a template SQL which should save you a lot of time.

DECLARE
  l_insert_stmt VARCHAR2(4000);
  l_comma VARCHAR2(1) DEFAULT ' ';
  l_src_table VARCHAR2(500) := 'TABLE1';
  l_src_table_owner VARCHAR2(500) := 'DB1';
  l_target_table VARCHAR2(500) := 'TABLE2';
  l_target_table_owner VARCHAR2(500) := 'DB2';
BEGIN
  l_insert_stmt := 'INSERT INTO ' || l_target_table || ' ( ';
  FOR rec IN (SELECT column_name FROM all_tab_columns
              WHERE TABLE_name = l_target_table AND owner = l_target_table_owner)
  LOOP
     l_insert_stmt := l_insert_stmt || l_comma || rec.column_name;
     l_comma := ',';
  END LOOP;
  l_insert_stmt := l_insert_stmt || ' ) ';

  l_insert_stmt := l_insert_stmt || ' SELECT ';
  l_comma := ' ';
  FOR rec IN (SELECT column_name FROM all_tab_columns
              WHERE TABLE_name = l_src_table AND owner = l_src_table_owner)
  LOOP
     l_insert_stmt := l_insert_stmt || l_comma || rec.column_name;
     l_comma := ',';
  END LOOP;
  l_insert_stmt := l_insert_stmt || ' FROM ' || l_src_table;

  dbms_output.put_line(l_insert_stmt);
END;

If you need to do this often enough,then another option is to use a schema synchronization tool. Toad, dbsolo and probably a few other tools can be used. It has saved me a lot of time and effort.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top