简体   繁体   中英

Copying contents of table A to table B (one more column than table A)

In our application, we have two sets of tables: One set of working tables (with the data that is currently analyzed) and another set of archive tables (with all data that has even been analyzed, same table-name but with a a_ prefix). The structure of the tables is the same, except that the archive tables have an extra column run_id to distinguish between different sets of data.

Currently, we have a SQL script that copies the contents over with statements similar to this:

insert into a_deals (run_id, deal_id, <more columns>) 
select maxrun, deal_id, <more columns> 
from deals,
  (select    max(run_id) maxrun from batch_runs);   

This works fine, but whenever we add a new column to the table, we also have to mpdify the script. Is there a better way to do this that is stable when we have new columns? (Of course the structures have to match, but we'd like to be able not to have to change the script as well.)

FWIW, we're using Oracle as our RDBMS.

Following up on the first answer, you could build a pl/sql procedure which will read all_tab_columns to build the insert statement, then execute immediate. Not too hard, but be careful about what input parameters you allow (table_name and the like) and who can run it since it could provide a great opportunity for SQL Injection.

If the 2 tables have the SAME columns in the same order (column_id from all_tab_columns) except for this run_id in front, then you can do something like:

insert into a_deals
select (select max(run_id) from maxrun), d.*
from deals
where ...;

This is a lazy approach imo, and you'll want to ensure that the columns are in the same position for both tables as part of this script (inspect all_tab_columns). 2 varchar2 fields that are switched will lead to data inserted into incorrect fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM