【数据库】用游标简单修改大批量数据(三千七百万数据)

对于大表批量操作建议用游标操作.

如对以下大表的操作,直接update耗时约16min;运用游标后耗时3min左右

注意:游标打开后,服务器会专门为游标分配一定的内存空间存放游标操作的数据结果集,同时使用游标也会对某些数据进行封锁。所以游标一旦用过,应及时关闭,避免服务器资源浪费

关于游标的具体使用请移步参考:https://www.cnblogs.com/jdzhang/p/7576520.html



declare
  po_success integer;
  po_info    varchar2(2000);
  cursor cur_cdr is
  --查询目标数据
  SELECT ID FROM LISTING_QUEUE_LAZ where  SALE_SITE='SGAMZ';
   
  type type_listing_queue_laz_id is table of LISTING_QUEUE_LAZ.ID%type;
  table_listing_queue_laz_id type_listing_queue_laz_id;


  ln_cnt number := 0;

begin
  open cur_cdr;
  loop
    fetch cur_cdr bulk collect
      into table_listing_queue_laz_id limit 10000;
  
    ln_cnt := ln_cnt + table_listing_queue_laz_id.count;
  
    -- forall i in 1 .. table_rowid.count
    For i In 1 .. table_listing_queue_laz_id.Count loop
    --执行目标操作
    UPDATE LISTING_QUEUE_LAZ SET SALE_SITE='SG' WHERE ID=table_listing_queue_laz_id(i);
        ln_cnt := ln_cnt - 1;
    end loop;
    commit;
    exit when cur_cdr%notfound or cur_cdr%notfound is null;
  end loop;
  --使用结束应立即关闭
  close cur_cdr;
  commit;

  --打印日志
  po_success := 0;
  po_info    := '执行成功';
  -- 取消注释打印日志
  -- dbms_output.put_line('执行结果: code:' || po_success || ' msg:' || po_info);
exception
  when others then
    if cur_cdr%isopen then
      close cur_cdr;
    end if;
    rollback;
    po_success := 1;
    po_info    := '执行失败,失败信息为:' || sqlerrm;
   -- 取消注释打印日志
   -- dbms_output.put_line('执行结果: code:' || po_success || ' msg:' || po_info);
end;

猜你喜欢

转载自blog.csdn.net/CountryShi/article/details/107056338
今日推荐