Skip to content
Advertisement

How to generate INSERT Statements with Subqueries in Oracle SQL Developer?

I need to move some data from Environment A to Environment B. So far, so easy. But some of the columns have FK Constraints and unfortunately the lookup data is already on Environment B and has different PKs. Lucky me, there are other unique columns I could do a mapping on. Therefore I wonder if SQL Developer has an export feature which allows me to replace certain column values by subqueries. To make it clear, I’m looking for a SQL Developer Feature, Query or similar which generates INSERT Statements that look like this:

INSERT INTO table_name(col1, col2, fkcol) 
VALUES('value', 'value', (SELECT id FROM lookup_table WHERE unique_value = 'unique'))

My best approach was to try to generate them by hand, like this:

SELECT 
    'INSERT INTO table_name(col1, col2, fkcol) '  
    || 'VALUES( '
    || (SELECT LISTAGG(col1, col2, 
'SELECT id FROM lookup_table 
WHERE unique_value = ''' || lookup_table.uniquevalue || '''', ', ') 
WITHIN GROUP(ORDER BY col1) 
FROM table_name INNER JOIN lookup_table ON table_name.fkcol = lookup_table.id)
    || ' );'
    FROM table_name;

Which is absolutely a pain. Do you know something better to achive this without approaching the other db?

Advertisement

Answer

Simple write a query that produces the required data (with the mapped key) using a join of both tables.

For example (see the sample data below) such query (mapping the unique_value to the id):

select 
  tab.col1, tab.col2, lookup_table.id fkcol 
from tab
join lookup_table
on tab.fkcol = lookup_table.unique_value

      COL1 COL2        FKCOL
---------- ------ ----------
         1 value1         11
         2 value2         12

Now you can use the normal SQL Developer export feature in the INSERT format, which would yield following script – if you want to transer it to other DB or insert it direct with INSERT ... SELECT.

Insert into TABLE_NAME (COL1,COL2,FKCOL) values ('1','value1','11');
Insert into TABLE_NAME (COL1,COL2,FKCOL) values ('2','value2','12');

Sample Data

select * from tab;
      COL1 COL2   FKCOL  
---------- ------ -------
         1 value1 unique 
         2 value2 unique2
         
select * from  lookup_table       
       ID UNIQUE_
---------- -------
        11 unique 
        12 unique2
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement