【问题标题】:How to write a FOR EACH loop in PL/SQL?如何在 PL/SQL 中编写 FOR EACH 循环?
【发布时间】:2012-04-07 06:54:24
【问题描述】:

是否可以在 PL/SQL 数组上运行 for each 循环?

【问题讨论】:

标签: sql plsql


【解决方案1】:
for i in my_array.first ..my_array.last loop
  --do_something with my_array(i);
end loop;

【讨论】:

  • 正如 ceving 链接中的一些 cmets 所述,如果 my_array 为空,则会返回错误。对于这种情况,最好使用FOR i IN 1 .. my_array.COUNT
【解决方案2】:

不可能使用 FOR 循环遍历具有非数字索引的关联数组。下面的解决方案工作得很好。

-- for-each key in (associative-array) loop ... 
declare
    type items_type is table of varchar2(32) index by varchar2(32);
    items items_type;
begin
    items('10') := 'item 10';
    items('20') := 'item 20';
    items('30') := 'item 30';
    dbms_output.put_line('items=' || items.count); 

    <<for_each>> declare key varchar2(32); begin loop 
        key := case when key is null then items.first else items.next(key) end; 
        exit when key is null;
        dbms_output.put_line('item(' || key || ')=' || items(key));
        --do something with an item
    end loop; end for_each;
end;

【讨论】:

    猜你喜欢
    • 2013-08-25
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    相关资源
    最近更新 更多