How does the oracle iterate over the values of an array?
In Oracle, looping can be used to iterate through array values. Here are two commonly used methods:
- Traverse the array using a FOR loop.
DECLARE
TYPE array_type IS VARRAY(3) OF VARCHAR2(10);
my_array array_type := array_type('value1', 'value2', 'value3');
BEGIN
FOR i IN 1..my_array.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(my_array(i));
END LOOP;
END;
In the example above, an array type named array_type is defined first, followed by the creation of an array called my_array with three elements. Next, a FOR loop is used to iterate through the array indices from 1 to the number of elements in the array (my_array.COUNT), accessing the values at each index and printing them out.
- Iterate through an array using a FOREACH loop.
DECLARE
TYPE array_type IS VARRAY(3) OF VARCHAR2(10);
my_array array_type := array_type('value1', 'value2', 'value3');
BEGIN
FOR item IN my_array.FIRST..my_array.LAST LOOP
DBMS_OUTPUT.PUT_LINE(my_array(item));
END LOOP;
END;
In the example above, an array type array_type is first defined, and then an array my_array containing three elements is created. Next, a FOREACH loop is used to iterate through the array indexes, from the first element of the array (my_array.FIRST) to the last element (my_array.LAST), accessing the array values by index and printing them out.
– The choice between using a FOR loop or a FOREACH loop to iterate through array values depends on personal preference and needs.