将行移动到另一个表

时间:2015-10-01 10:07:07

标签: sql oracle oracle11g

我希望将行从一个表移动到另一个表(以便将未使用的数据移动到历史存储中)。

如何以最聪明的方式做到这一点?

我找到了这样的解决方案,但看起来它不适用于Oracle方言

    INSERT dbo.CustomersInactive (
      CustomerID,
      FirstName,
      LastName
) SELECT 
            CustomerID,
            FirstName,
            Lastname
      FROM    (
           DELETE dbo.CustomersActive
           OUTPUT
                   DELETED.CustomerID,

2 个答案:

答案 0 :(得分:1)

此解决方案似乎有效:

DECLARE
   TYPE CustomerSet IS TABLE OF CustomersActive%ROWTYPE;
   inactive CustomerSet;
BEGIN

delete from CustomersActive returning  CustomerID,FirstName,Lastname bulk collect into inactive;

FOR i IN inactive.FIRST .. inactive.LAST LOOP  
        insert into CustomersInactive values (inactive(i).CustomerID,inactive(i).FirstName,inactive(i).Lastname);
END LOOP;        

END;

答案 1 :(得分:0)

我希望你需要这样的情况:

--init objects
create table active_cust
(cust_id integer,
 name varchar2(100 char)
 );

create table inactive_cust as 
select * 
  from active_cust 
 where 1=2;

--init data
insert into active_cust values (1, 'Przemo');
insert into active_cust values (2,'Pan Miecio');
insert into active_cust values (3,'Pan Franio');

insert into inactive_cust values (3,'Pan Franio');

--merge active and inactive
merge into inactive_cust dest
using (select * from active_cust) srce
on (srce.cust_id = dest.cust_id)
when not matched then insert values
  (srce.cust_id, srce.name )
  --here specify conditions on which customer is being
  --accounted as inactive
  /*where srce.some_status_date < sysdate - 100 */
  ;--only two rows merged as we have >Pan Franio< already in a list of inactive customers!

--now as we have all inactive customers in inactive_cust table, delete from active_cust where id is present in inactive_cust
delete from active_cust ac
 where ac.cust_id in (select cust_id
                            from inactive_cust);

drop table active_cust;
drop table inactive_cust;