你好,游客 登录 注册 搜索
背景:
阅读新闻

多行数据的批处理之bulk collect

[日期:2015-07-15] 来源:Linux社区  作者:jeanron100 [字体:大 中 小]

在写pl/sql的时候,很多时候都会用比较经典的模式,定义一个游标cursor,然后循环从游标中取值进行处理。
 类似下面的格式
declare
 cursor xxxx is xxxxx;
 begin
 loop cur in xxxxx loop
 xxxxx
 end loop;
 end;
 /

如果cursor中包含的数据太多的时候,可能会有性能问题,性能的考虑主要在于pl/sql引擎和sql引擎的切换,和编程中的上下文环境是类似的。
 这个时候可以考虑采用bulk collect 的方式直接一次性读取数据岛缓存然后从缓存中进一步处理。
 这种方式可以打个比方比较形象,比如 你带着一个新人去完成一个任务,可能一天他要问你100个问题,你是希望他每隔几分钟想到了就问你呢,还是让他自己把问题积累起来,专门设定一个时间来集中回答呢。可能你在忙另外一个事情,他问你一个问题,这个时候就会有上下文环境的切换,等你回答了之后,继续工作的时候,又一个问题来了,这时候又得进行一次切换。。。。
 比方说我们设定一个表test,希望把test里面的数据选择性的插入到test_all中去
 实现的原始Pl/sql如下:
declare
 cursor test_cursors is select object_id,object_name from test;
 begin
 for test_cursor in test_cursors loop
 dbms_output.put_line('object_id: '||test_cursor.object_id);
 insert into test_all values(test_cursor.object_id,test_cursor.object_name);
 end loop;
 commit;
 end;
 /

如果采用bulk collect 方式,就会是如下的方式:
 declare
  type id_t is table of test.object_id%type;
  type name_t is table of test.object_name%type;
  object_id id_t;
  object_name name_t;
  cursor test_cursors is select object_id,object_name from test;
  begin
  open test_cursors;
 fetch test_cursors bulk collect into object_id,object_name;
 close test_cursors;
  for i in object_id.FIRST .. object_id.LAST loop
  dbms_output.put_line('object_id: '||object_id(i));
  insert into test_all values(object_id(i),object_name(i));
  end loop;
  commit;
  end;
  /


或者采用隐式游标的方式:
 declare
  type id_t is table of test.object_id%type;
  type name_t is table of test.object_name%type;
  object_id id_t;
  object_name name_t;
  begin
  select object_id,object_name bulk collect into object_id,object_name from test where rownum<20;
  for i in object_id.FIRST .. object_id.LAST loop
  dbms_output.put_line('object_id: '||object_id(i));
  insert into test_all values(object_id(i),object_name(i));
  end loop;
  commit;
  end;
  /

更多Oracle相关信息见Oracle 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=12

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-07/119948.htm

linux
相关资讯       bulk collect 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款