Associative Arrays in Oracle PL/SQL: The Professional Approach - Bottom to top traverse of an associative array using Oracle PL/SQL (Page 3 of 5 )
In the last sections, we have already seen several pre-defined members associated with associative arrays. Now, let us look into the same scenario with a small difference in traversing.
The last two sections concentrated on a top-down approach to traversing an associative array. Now, we shall focus on a bottom-top approach to traversing the same. Let us first go through the code:
declare
type year_type is table of number index by binary_integer;
year_sales year_type;
tot_sales number := 0;
i number;
begin
year_sales(1990) := 34000;
year_sales(1991) := 45000;
year_sales(1992) := 43000;
year_sales(1996) := 13000;
year_sales(1998) := 53000;
i := year_sales.last;
while i >= year_sales.first
loop
tot_sales := tot_sales + year_sales(i);
dbms_output.put_line('Sales of ' || i || ': ' ||
year_sales(i));
i := year_sales.prior(i);
end loop;
dbms_output.put_line('Total sales: ' || tot_sales);
dbms_output.put_line('Avg sales: ' ||
(tot_sales/year_sales.count) );
end;
Shown below are the only modifications I made to the above code. I replaced the following:
i := year_sales.first;
while i <= year_sales.last
loop
tot_sales := tot_sales + year_sales(i);
dbms_output.put_line('Sales of ' || i || ': ' ||
year_sales(i));
i := year_sales.next(i);
end loop;
with this:
i := year_sales.last;
while i >= year_sales.first
loop
tot_sales := tot_sales + year_sales(i);
dbms_output.put_line('Sales of ' || i || ': ' ||
year_sales(i));
i := year_sales.prior(i);
end loop;
Please observe the color highlighting in the code fragments above. The rest is the same, and I leave it for you to understand.
Next: Deleting individual elements in an associative array using Oracle PL/SQL >>
More Oracle Articles
More By Jagadish Chatarji