如何复制表中除应该更改的单个列以外的所有数据
问题描述:
我有一个关于对具有不同数据结构(Oracle)的表进行统一插入查询的问题 结构(Oracle)。让我详细说明一个例子:如何复制表中除应该更改的单个列以外的所有数据
tb_customers (
id NUMBER(3), name VARCHAR2(40), archive_id NUMBER(3)
)
tb_suppliers (
id NUMBER(3), name VARCHAR2(40), contact VARCHAR2(40), xxx, xxx,
archive_id NUMBER(3)
)
所有表中唯一存在的列是[archive_id]。计划是通过将所有记录复制(复制)到不同的数据库分区并相应地增加这些记录的archive_id来创建数据集的新归档。 [archive_id]始终是主键的一部分。
我的问题是用select语句来做实际的数据重复。因为列是可变的,所以我努力想出一个统一的select语句来复制数据并更新archive_id。
一个解决方案(的作品),是迭代在存储过程中的所有表,并做了:
CREATE TABLE temp as (SELECT * from ORIGINAL_TABLE);
UPDATE temp SET archive_id=something;
INSERT INTO ORIGINAL_TABLE (select * from temp);
DROP TABLE temp;
我不喜欢这种解决方案非常的DDL命令弄脏所有还原点。
有没有其他人有任何解决方案?
答
如何为每个基表创建一个全局临时表?
create global temporary table tb_customers$ as select * from tb_customers;
create global temporary table tb_suppliers$ as select * from tb_suppliers;
您不需要每次都创建和删除这些内容,只是将它们保留原样。
你的存档过程是那么单一交易...
insert into tb_customers$ as select * from tb_customers;
update tb_customers$ set archive_id = :v_new_archive_id;
insert into tb_customers select * from tb_customers$;
insert into tb_suppliers$ as select * from tb_suppliers;
update tb_suppliers$ set archive_id = :v_new_archive_id;
insert into tb_suppliers select * from tb_suppliers$;
commit; -- this will clear the global temporary tables
希望这有助于。
答
我会建议没有一个单一的SQL语句的所有表,只是使用和插入。
insert into tb_customers_2
select id, name, 'new_archive_id' from tb_customers;
insert into tb_suppliers_2
select id, name, contact, xxx, xxx, 'new_archive_id' from tb_suppliers;
或者,如果你真的需要所有的人都至少预先创建所有的临时表的单个SQL语句(如临时表),并让他们在原地下一次。然后,只需使用动态sql来引用临时表。
insert into ORIGINAL_TABLE_TEMP (SELECT * from ORIGINAL_TABLE);
UPDATE ORIGINAL_TABLE_TEMP SET archive_id=something;
INSERT INTO NEW_TABLE (select * from ORIGINAL_TABLE_TEMP);
我想你的示例SQL的倒数第二行应该是: INSERT INTO ** ** TARGET_TABLE(选择温度*); – ntziolis 2010-04-23 07:23:21
ty指出,固定 – twiga 2010-05-06 11:37:09