问题是这样的:数据库中有A(id,typeid,publishDate)表和(id,typeid,publishDate)表,结构是一样的,由于A表中的数据太大,并且多数数据不使用了,故想把它当中的部分数据转移到B表中。
A表中的类型有type1、type2和type3三种类型,转移的要求是类型记录数大于1000条的(按发布时间(publishdate)降序排列)的数据(即当类型的记录数小于1000条就不用转移)。
由于数据量太大,所以使用转移一条到B表后,再删除A表那条数据,使用事务保证数据的正确转移。
求实现此功能的存储过程。

解决方案 »

  1.   

    @gxlineji()   
    谢谢你的关注。。@intotheheart()
    请问是delete一下就把符合要求的全部删除吗?
    如果这样使用事务会不会出问题,因为数据量太大,谢谢
      

  2.   

    insert into b select * from a m where (select count(*) from a n where m.publishDate>n.publishDate and m.typeid=n.typeid)>=1000;--不包含1000
      

  3.   

    delete from a m where (select count(*) from a n where m.publishDate>n.publishDate and m.typeid=n.typeid)>=1000;--不包含1000
      

  4.   

    错了,应该是小于才是降序.
    insert into b select * from a m where (select count(*) from a n where m.publishDate<n.publishDate and m.typeid=n.typeid)>=1000;--不包含1000
    delete from a m where (select count(*) from a n where m.publishDate<n.publishDate and m.typeid=n.typeid)>=1000;--不包含1000
      

  5.   

    @shan1119 
    谢谢你,你这个语句本身不错,
    但是我这里的数据是快到30W条了
    执行这个语句会出问题的   不知道要多久才能完成。
    我单独执行删除的语句等了很久都没有执行完。。能不能换一种办法?
      

  6.   

    不知是否符合搂主的要求,transaction是按每一个typeid来做的,如果中间失败,会回滚出异常的那个typeid,不会影响别的typeid。
    用记事本写的,没有跑过,如有细微错误如拼写错误等,请搂主自己修改吧。
    另,请将Output功能打开。
    procedure move_data
    is pragma autonomous_transaction;
    begin
        for rec_data in (
            select typeid as type id,
                   count(1) as record_count 
              from a)
        loop
            begin
                set savepoint sp_each_loop;
                if rec_data.record_count  > 1000 then
                    insert into b
    select * from a 
                       where rownum > 1000
     order by a.publishDate desc;

    delete b
     where rownum > 1000
     order by b.publishDate desc;

    commit;
    dbms_output.put_line('Move data of typeid: ' || rec_data.typeid || ' successfully!');
        end if;
        dbms_output.put_line('Records of typeid: ' || rec_data.typeid || ' is less than 1000.');
    exception
                when others then
        rollback to sp_each_loop;
                dbms_output.punt_line('Error occured when processing typeid: ' || rec_data.typeid || '.');
    end;
        end loop;
    exception
        when others then
    dbms_output.put_line(substr(sqlerrm, 1, 4000));
    end;
      

  7.   

    @sky_boxer(饿鱼骨头) 
    谢谢,先给分 
    我再试