PL/SQL中的BULK COLLECT/FORALL

本文参考文档:bulk collect and forall

我们通常会在PL/SQL中同时使用PL/SQL和SQL statements。PL/SQL statements are run by the PL/SQL statement executor; SQL statements are run by the SQL statement executor. When the PL/SQL runtime engine encounters a SQL statement, it stops and passes the SQL statement over to the SQL engine. The SQL engine executes the SQL statement and returns information back to the PL/SQL engine. 而这降低了效率。BULK COLLECT和FORALL之所以能优化批量操作的性能,原因在于使用它们可以避免the context switching between PL/SQL and SQL by doing as much of the work as possible within SQL.

BULK COLLECT:  SELECT statements that retrieve multiple rows with a single fetch, improving the speed of data retrieval

FORALL: INSERTs, UPDATEs, and DELETEs that use collections to change multiple rows of data very quickly

下面是使用两者的例子:

  CREATE OR REPLACE PROCEDURE increase_salary (
      department_id_in   IN employees.department_id%TYPE,
      increase_pct_in    IN NUMBER)
   IS
      TYPE employee_ids_t IS TABLE OF employees.employee_id%TYPE
              INDEX BY PLS_INTEGER; 
    l_employee_ids   employee_ids_t;
    l_eligible_ids   employee_ids_t;

     l_eligible       BOOLEAN;
  BEGIN
     SELECT employee_id
       BULK COLLECT INTO l_employee_ids -- 重点
       FROM employees
      WHERE department_id = increase_salary.department_id_in;

     FOR indx IN 1 .. l_employee_ids.COUNT
     LOOP
        check_eligibility (l_employee_ids (indx),
                           increase_pct_in,
                           l_eligible);

        IF l_eligible
        THEN
           l_eligible_ids (l_eligible_ids.COUNT + 1) :=
              l_employee_ids (indx);
        END IF;
     END LOOP;

     FORALL indx IN 1 .. l_eligible_ids.COUNT -- 重点
        UPDATE employees emp
           SET emp.salary =
                    emp.salary
                  + emp.salary * increase_salary.increase_pct_in
         WHERE emp.employee_id = l_eligible_ids (indx);
  END increase_salary;

另外我们在使用游标读取数据时,Oracle会自动使用类似BULK COLLECT查询来优化FOR LOOP的性能。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值