Oracle PL/SQL - FIRST and LAST Methods for Nested Table

Introduction

For a nested table, LAST equals COUNT unless you delete elements from its middle, in which case LAST is larger than COUNT.

The following code prints the nested table team using a FOR LOOP statement with the bounds team.FIRST and team.LAST.

Demo

SQL>
SQL> DECLARE--   w w  w.  j a v a 2  s.  c o m
  2    TYPE StringList IS TABLE OF VARCHAR2(15);
  3    team StringList;
  4
  5    PROCEDURE print_team (heading VARCHAR2) IS
  6    BEGIN
  7      DBMS_OUTPUT.PUT_LINE(heading);
  8
  9      IF team IS NULL THEN
 10        DBMS_OUTPUT.PUT_LINE('Does not exist');
 11      ELSIF team.FIRST IS NULL THEN
 12        DBMS_OUTPUT.PUT_LINE('Has no members');
 13      ELSE
 14        FOR i IN team.FIRST..team.LAST LOOP
 15          DBMS_OUTPUT.PUT(i || '. ');
 16          IF team.EXISTS(i) THEN
 17            DBMS_OUTPUT.PUT_LINE(team(i));
 18          ELSE
 19            DBMS_OUTPUT.PUT_LINE('(to be hired)');
 20          END IF;
 21        END LOOP;
 22      END IF;
 23    END;
 24  BEGIN
 25    print_team('Team Status:');
 26
 27    team := StringList();  -- Team is funded, but nobody is on it.
 28    print_team('Team Status:');
 29
 30    team := StringList('A', 'B', 'C', 'D');  -- Add members.
 31    print_team('Initial Team:');
 32
 33    team.DELETE(2,3);  -- Remove 2nd and 3rd members.
 34    print_team('Current Team:');
 35  END;
 36  /
Team Status:
Does not exist
Team Status:
Has no members
Initial Team:
1. A
2. B
3. C
4. D
Current Team:
1. A
2. (to be hired)
3. (to be hired)
4. D

PL/SQL procedure successfully completed.

SQL>