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



如何使用BULK COLLECT和FORALL来替换PL/SQL中的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;

谢谢。

这可以在一个更新语句中完成:

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

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

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;

相关内容

  • 没有找到相关文章

最新更新