如何在PL / SQL中使用BULK COLLECT和FORALL替换CURSOR FOR LOOP?

时间:2014-09-23 16:25:11

标签: for-loop plsql forall bulk-collect

如何在PL / SQL中使用BULK COLLECT和FORALL替换CURSOR FOR LOOP?我想有一种更有效的方法来更新单个表中的记录。

假设我有以下PL / SQL代码:

DECLARE
   var_buy_more_shoes   inventory.buy_more_shoes%TYPE := NULL;
   var_buy_more_bananas   inventory.buy_more_bananas%TYPE := NULL;
   var_buy_more_iphone6s   inventory.buy_more_iphone6s%TYPE := NULL;

   CURSOR cur
   IS
      SELECT *
        FROM inventory
      FOR UPDATE;

BEGIN
   FOR rec IN cur
   LOOP
      IF rec.pair_of_shoes_left <= 100
      THEN
         var_buy_more_shoes := 'Yes';
      END IF;

      IF rec.weight_of_bananas_left <= 200
      THEN
         var_buy_more_bananas := 'Yes';
      END IF;

      IF rec.number_of_iphone6s_left <= 50
      THEN
         var_buy_more_iphone6s := 'Yes';
      END IF;

      UPDATE inventory a
         SET A.buy_more_shoes = var_buy_more_shoes,
             A.buy_more_bananas = var_buy_more_bananas,
             A.buy_more_iphone6s = var_buy_more_iphone6s
       WHERE CURRENT OF cur;
   END LOOP;

   COMMIT;
END;

感谢。

2 个答案:

答案 0 :(得分:5)

这可以在一个更新声明中完成:

UPDATE inventory
SET buy_more_shoes    = CASE
                          WHEN pair_of_shoes_left <= 100 THEN 'Yes'
                          ELSE NULL
                        END
  , buy_more_bananas  = CASE
                          WHEN weight_of_bananas_left <= 200 THEN 'Yes'
                          ELSE NULL
                        END
  , buy_more_iphone6s = CASE
                          WHEN number_of_iphone6s_left <= 50 THEN 'Yes'
                          ELSE NULL
                        END

答案 1 :(得分:0)

您可以创建一个表对象和集合,然后将查询结果批量收集到表集合中。

CREATE OR REPLACE EDITIONABLE TYPE  "F_OBJ" AS OBJECT (
Employer_name VARCHAR2(100),
Employer_id VARCHAR2 ( 100 ))

CREATE OR REPLACE EDITIONABLE TYPE  "F_TAB" as table of _OBJ

create or replace function "fname"
return f_tab
is
 l_f_tab f_tab;

begin
SELECT f_obj(employee_name, employee_id) bulk collect into f_tab from employee_table
return f_tab;