HomeOracle Page 3 - Associative Arrays in Oracle PL/SQL: The Professional Approach
Bottom to top traverse of an associative array using Oracle PL/SQL - Oracle
This is the second article in a series focusing on associative arrays. In this article, we shall examine recommended methodologies for working with associative arrays efficiently.
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.