动态SQL完成大表数据的迁移

目前需求是根据源表数据如salary>10000的数据插入目标表中,目标表根据需要指定,且插入指定N条数据后提交。

对于此类问题可以用insert into select方法但需要按指定N条数据提交,说明表中数据量很大,插入时应批量提取,再按

指定条数插入新表,且批量提取数据时也应根据数据大小分批提取,于是考虑在动态sql中使用bulk collect into + limit的方法

具体实例如下


drop table emp_bak;
create table emp_bak
  as select  first_name
            ,salary
            ,rownum  rnid
  from employees
  where 1 != 1;

declare
  SOURCE_TABLE varchar(100);
  TAG_A VARCHAR(100);
  C_COUNT  VARCHAR(100);
  v_query_sql   varchar2(500);
  v_query_rn   varchar2(100);
  
  type delArray1 is table of hr.employees.first_name%type index by binary_integer;
  type delArray2 is table of hr.employees.salary%type index by binary_integer;
  type delArray3 is table of  hr.employees.employee_id%type index by binary_integer;
  first_name delArray1;
  salary delArray2;
  rnid delArray3;
  rnd number;
 
  TYPE i_cursor_type IS REF CURSOR;
  my_cursor i_cursor_type;
  begin 
       SOURCE_TABLE := 'employees';
       TAG_A := 'emp_bak';
       C_COUNT  := 10;
       v_query_rn :=
        'select   count(*)
       from '||SOURCE_TABLE||'
       where salary > 10000';
      
       v_query_sql :=
        'select    first_name
                  ,salary
                  ,rownum
       from '||SOURCE_TABLE||'
       where salary > 10000';
      
      open   my_cursor  for v_query_sql;
      execute immediate v_query_rn into rnd;
      for i in 1..rnd loop
        fetch my_cursor bulk collect into first_name,salary,rnid limit 10;
        for i in 1..first_name.count
        loop        
         execute immediate  'insert into hr.'|| TAG_A||' values (:1, :2, :3)'
                          using first_name(i),salary(i),rnid(i);
        end loop;
       end loop;
      close my_cursor;          
  end;
 
 select count(*) from emp_bak;

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/750077/viewspace-2074785/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/750077/viewspace-2074785/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值