Re: most idiomatic way to iterate over an associative array?

From: Robert Klemme <shortcutter_at_googlemail.com>
Date: Wed, 7 May 2008 01:07:27 -0700 (PDT)
Message-ID: <afda6bc0-f447-4564-8ccd-78dd07425067@25g2000hsx.googlegroups.com>


On May 7, 6:51 am, m..._at_pixar.com wrote:
> This is what I'm doing now... is there a better way?
> It would be great if there were some construct such
> as 'for i in x begin ... end;'
>
> i := x.first;
> loop
> dbms_output.put_line(i);
> exit when i = x.last;
> i := x.next(i);
> end loop;
>
> Many TIA!
> Mark

This will break for empty collections. You can do

SQL> set serverout on
SQL> DECLARE TYPE population_type IS TABLE OF NUMBER INDEX BY VARCHAR2(64);
  2 continent_population population_type;   3 which VARCHAR2(64);
  4 BEGIN
  5 dbms_output.put_line('-----------');   6
  7 which := continent_population.FIRST;   8 while which is not null loop
  9 dbms_output.put_line(which || ' -> ' || continent_population(which));
 10 which := continent_population.NEXT(which);  11 end loop;
 12
 13 dbms_output.put_line('-----------');  14
 15 continent_population('Australia') := 30000000;  16 continent_population('Antarctica') := 1000; -- Creates new entry
 17 continent_population('Antarctica') := 1001; -- Replaces previous value
 18
 19 which := continent_population.FIRST;  20 while which is not null loop
 21 dbms_output.put_line(which || ' -> ' || continent_population(which));
 22 which := continent_population.NEXT(which);  23 end loop;
 24
 25 dbms_output.put_line('-----------');  26 END;
 27 /




Antarctica -> 1001
Australia -> 30000000

PL/SQL procedure successfully completed.

SQL> Cheers

robert

see
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/collections.htm#sthref1022 http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/collections.htm#sthref1146 Received on Wed May 07 2008 - 03:07:27 CDT

Original text of this message