本文共 1864 字,大约阅读时间需要 6 分钟。
在写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; /来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/23718752/viewspace-1289696/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/23718752/viewspace-1289696/