重置PL / SQL中的关联数组?

时间:2009-11-13 20:47:51

标签: oracle plsql

这是“必须有更好的方式”问题之一。让我设置问题,然后我会给你我的黑客解决方案,也许你可以建议一个更好的解决方案。谢谢!

让我们把这个小小的PL / SQL

DECLARE
 TYPE foo_record IS RECORD (foo%type, bar%type);
 TYPE foo_records IS TABLE OF foo_record INDEX BY PLS_INTEGER;
 arr_foos foo_records;

 CURSOR monkeys is SELECT primates FROM zoo;
 row_monkey monkeys%rowtype;
BEGIN
 FOR row_monkey IN monkeys loop
  /*
    at this point in each iteration I need to have the associative array 
    arr_foos in its original state. if this were java, I'd declare it 
    right here and its scope would be limited to this iteration. However, 
    this is not java, so the scope of the array is effectively global and 
    I can't have one iteration's data meddle with the next.
  */
  null;
 END LOOP;
END;

这有意义吗?我基本上需要将其重置为某种东西。如果它是一个从零开始的数字,我可以说数字:= 0;在每次迭代的顶部并完成它。但这不是一个数字,它是一种我可以用干净重置的类型:= 0。

无论如何,在我的黑客上:

DECLARE
 TYPE foo_record IS RECORD (foo%type, bar%type);
 TYPE foo_records IS TABLE OF foo_record INDEX BY PLS_INTEGER;
 arr_foos foo_records;
 arr_foos_reset foo_records;

 CURSOR monkeys is SELECT primates FROM zoo;
 row_monkey monkeys%rowtype;
BEGIN
 FOR row_monkey IN monkeys loop
  arr_foos := arr_foos_reset;
  null;
 END LOOP;
END;

我认为如果我能够设法在原始状态下保留相同类型的成员,那么我可以将工作变量设置回原始值的任何值。并且,令人惊讶的是,它有效(我认为。)但是必须有更好的方法。有人可以帮忙吗?

T'anks!

2 个答案:

答案 0 :(得分:27)

最简单的方法:

arr_foos.Delete();

其他方法是在FOR循环内声明变量。这样,它将为每次传递重新创建。

像这样:

DECLARE
 TYPE foo_record IS RECORD (foo%type, bar%type);
 TYPE foo_records IS TABLE OF foo_record INDEX BY PLS_INTEGER;     

 CURSOR monkeys is SELECT primates FROM zoo;
 row_monkey monkeys%rowtype;
BEGIN
 FOR row_monkey IN monkeys loop
  DECLARE
    arr_foos foo_records;
  BEGIN
    null;
  END;
 END LOOP;
END;

答案 1 :(得分:3)

您是否要将动物园表中的数据读入集合?然后有一个更好的方法:

DECLARE
  type foos_ts is table of zoo.foo%type index by pls_integer;
  foos foos_t;
BEGIN
  select foo
  bulk collect into foos
  from zoo;
  ...
END;

批量收集在获取之前自动清除集合,并且它比在循环中逐行读取更快。不幸的是,它无法处理记录,因此每个字段都需要几个PL / SQL表。

您可以在此处找到更多信息:Retrieving Query Results into Collections with the BULK COLLECT Clause