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

ste*_*eve 9 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;
Run Code Online (Sandbox Code Playgroud)

那有意义吗?我基本上需要将其重置为某种东西.如果它是一个从零开始的数字,我可以说数字:= 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;
Run Code Online (Sandbox Code Playgroud)

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

T'anks!

Maj*_*kel 27

最简单的方法:

arr_foos.Delete();
Run Code Online (Sandbox Code Playgroud)

其他方法是在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;
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!在BEGIN之后我没有意识到你可以说DECLARE.(: (2认同)
  • 你可以嵌套任意次.这样你也可以在较小的代码块中捕获异常(比如C#或Java中的try/catch).在我看来非常有用的功能. (2认同)