How to write FOR EACH loop in PL / SQL?

Is it possible to run a loop for each loop in a PL / SQL array?

+5
source share
2 answers
for i in my_array.first ..my_array.last loop
  --do_something with my_array(i);
end loop;
+10
source

It is not possible to iterate over associative arrays with a non-numeric index with a FOR loop. The solution above works fine.

-- 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;
0
source

All Articles