You have a collection, and you need to determine the total number of elements in the collection.
Invoke the built-in COUNT
method on the collection. For example, the following code creates two collections: a varying array and an INDEX BY
array. The code then invokes the COUNT
method on both collections, doing so before and after adding some records to each.
DECLARE
TYPE vtype IS VARRAY(3) OF DATE;
TYPE ctype IS TABLE OF DATE INDEX BY BINARY_INTEGER;
vdates vtype := vtype (sysdate);
cdates ctype;
BEGIN
DBMS_OUTPUT.PUT_LINE ('vdates size is: ' || vdates.COUNT);
DBMS_OUTPUT.PUT_LINE ('cdates size is: ' || cdates.COUNT);
FOR i IN 1..3 LOOP
cdates(i) := SYSDATE + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE ('cdates size is: ' || cdates.COUNT);
END;
Executing this block of code produces the following results:
vdates size is: 1
cdates size is: 0
cdates size is: 3
The variable vdates
is initialized with one value, so its size is reported as 1 even though it is defined to hold a maximum of three values. The variable cdates
is not initialized, so it is first reported with a size of 0. The loop creates and sets three collection values, which increases its count to 3.
Assigning a value directly to cdates(i)
is allowed because cdates
is an INDEX BY
collection. Assigning a value to vdates
in the loop would cause an error because the array has only one defined value. See the EXTEND
method later in this chapter for more information on assigning values to non-INDEX BY
collections.
The COUNT
method is especially useful when used on a collection populated with a fetch from BULK COLLECT
statement to determine the number of records fetched or to process records in a FOR .. LOOP
.
18.191.159.139