10-14. Trimming a Collection

Problem

You need to remove one or more items from the end of a non-INDEX BY collection. The DELETE method will not work because it applies only to INDEX BY collections.

Solution

Use the TRIM method to remove one or more elements from the end of the collection. In this example, a VARRY is initialized with five elements. The TRIM method is used to remove elements from the end of the collection.

DECLARE

TYPE    vtype   IS VARRAY(5) OF DATE;
vdates  vtype := vtype (sysdate, sysdate+1, sysdate+2, sysdate+3, sysdate+4);

BEGIN

   DBMS_OUTPUT.PUT_LINE ('vdates size is: ' || vdates.COUNT);
   vdates.TRIM;
   DBMS_OUTPUT.PUT_LINE ('vdates size is: ' || vdates.COUNT);
   vdates.TRIM(2);
   DBMS_OUTPUT.PUT_LINE ('vdates size is: ' || vdates.COUNT);

END;

Executing this block of code produces the following results:

vdates size is: 5
vdates size is: 4
vdates size is: 2

How It Works

The TRIM method deletes elements from the end of the collection including elements not initialized. It accepts an optional parameter for the number of elements to delete; otherwise, it defaults to the last element. The TRIM method applies to TABLE and VARRAY collections that are not indexed. If the underlying TYPE definition does not contain the INDEX BY clause, then you can invoke TRIM.

The TRIM method is limited to removing elements from the end of a collection, whereas the DELETE method can remove elements anywhere in a collection. If you DELETE an element in the middle of a collection, then executing a FOR .. LOOP from one to the collection's COUNT will not work properly. First, if you attempt to access the element that was deleted without checking whether it EXISTS, an exception is thrown. Second, the COUNT method will return a value that is less than the collection's maximum index value, which means the FOR .. LOOP will not process all elements in the collection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.184.155