There are three types of collections: index-by tables (formerly known as PL/SQL tables), nested tables, and VARRAYs.
The following table compares these similar collection types.
Collections are implemented as TYPEs. Like any programmer-defined type, you must first define the type; then you can declare instances of that type. The TYPE definition can be stored in the database or declared in the PL/SQL program. Each instance of the TYPE is a collection.
The syntax for declaring an index-by table is:
TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY BINARY_INTEGER;
The syntax for a nested table is:
[CREATE [OR REPLACE]] TYPE type_name IS TABLE OF element_type [NOT NULL];
The syntax for a VARRAY is:
[CREATE [OR REPLACE]] TYPE type_name IS VARRAY | VARYING ARRAY (max_elements) OF element_type [NOT NULL];
The CREATE keyword defines the statement to be DDL and indicates that this type will exist in the database. The optional OR REPLACE keywords are used to rebuild an existing type, preserving the privileges. type_name is any valid identifier that will be used later to declare the collection. max_elements is the maximum size of the VARRAY. element_type is the type of the collection's elements. All elements are of a single type, which can be most scalar datatypes, an object type, or a REF object type. If the elements are objects, the object type itself cannot have an attribute that is a collection. Explicitly disallowed collection datatypes are BOOLEAN, NCHAR, NCLOB, NVARCHAR2, REF CURSOR, TABLE, and VARRAY.
NOT NULL indicates that a collection of this type cannot have any null elements. However, the collection can be atomically null (uninitialized).
Initializing an index-by table is trivial -- simply declaring it also initializes it. Initializing a nested table or VARRAY can be done explicitly, with a constructor, or implicitly with a fetch from the database or a direct assignment of another collection variable.
The constructor is a built-in function with the same name as the collection. It constructs the collection from the elements passed to it. We can create a nested table of colors and initialize it to three elements with a constructor:
DECLARE TYPE colors_tab_t IS TABLE OF VARCHAR2(30); colors_tab_t('RED','GREEN','BLUE'); BEGIN
We can create our nested table of colors and initialize it with a fetch from the database:
-- Create the nested table to exist in the database. CREATE TYPE colors_tab_t IS TABLE OF VARCHAR2(32); -- Create table with nested table type as column. CREATE TABLE color_models (model_type VARCHAR2(12) ,colors color_tab_t) NESTED TABLE colors STORE AS color_model_colors_tab; -- Add some data to the table. INSERT INTO color_models VALUES('RGB',color_tab_t('RED','GREEN','BLUE')); INSERT INTO color_models VALUES('CYMK',color_tab_t('CYAN','YELLOW', 'MAGENTA' 'BLACK')); -- Initialize a collection of colors from the table. DECLARE basic_colors colors_tab_t; BEGIN SELECT colors INTO basic_colors FROM color_models WHERE model_type = 'RGB'; ... END;
The third initialization technique is by assignment from an existing collection:
DECLARE basic_colors Color_tab_t := Color_tab_t ('RED','GREEN','BLUE'); my_colors Color_tab_t; BEGIN my_colors := basic_colors; my_colors(2) := 'MUSTARD';
Elements in an index-by table can be added simply by referencing new subscripts. To add elements to nested tables or VARRAYs, you must first enlarge the collection with the EXTEND function, and then you can assign a value to a new element using one of the methods described in the previous section.
Use the DELETE function to remove an element in a nested table regardless of its position. The TRIM function can also be used to remove elements, but only from the end of a collection. To avoid unexpected results, do not use both DELETE and TRIM on the same collection.
There are several psuedo-functions defined for collections. They include THE, CAST, MULTISET, and TABLE.
DECLARE birthdays Birthdate_t := Birthdate_t('24-SEP-1984', '19-JUN-1993'); BEGIN FOR the_rec IN (SELECT COLUMN_VALUE FROM TABLE(CAST(birthdays AS Birthdate_t)))
There are a number of built-in functions (methods) defined for all collections. These methods are called with dot notation:
The methods are described in the following table.
The EXISTS function returns a BOOLEAN and all other functions return BINARY_INTEGER. All parameters are of the BINARY_INTEGER type.
Only EXISTS can be used on uninitialized nested tables or VARRAYs. Other methods applied to these atomically null collections will raise the COLLECTION_IS_NULL exception.
DELETE and TRIM both remove elements from a nested table, but TRIM also removes the placeholder, while DELETE does not. This behavior may be confusing, since TRIM can remove previously DELETED elements.
Here is an example of some collection methods in use:
DECLARE TYPE colors_tab_t IS TABLE OF VARCHAR2(30); my_list colors_tab_t := colors_tab_t('RED','GREEN','BLUE'); element BINARY_INTEGER; BEGIN DBMS_OUTPUT.PUT_LINE('my_list has ' ||my_list.COUNT||' elements'); my_list.DELETE(2); -- delete element two DBMS_OUTPUT.PUT_LINE('my_list has ' ||my_list.COUNT||' elements'); FOR element IN my_list.FIRST..my_list.LAST LOOP IF my_list.EXISTS(element) THEN DBMS_OUTPUT.PUT_LINE(my_list(element) || ' Prior= '||my_list.PRIOR(element) || ' Next= ' ||my_list.NEXT(element)); ELSE DBMS_OUTPUT.PUT_LINE('Element '|| element ||' deleted. Prior= '||my_ list.PRIOR(element) || ' Next= '||my_list.NEXT(element)); END IF; END LOOP; END;
This example gives the output:
my_list has 3 elements my_list has 2 elements RED Prior= Next= 3 Element 2 deleted. Prior= 1 Next= 3 BLUE Prior= 1 Next=
As with other TYPEs in the database, you need the EXECUTE privilege on that TYPE in order to use a collection type created by another schema (user account) in the database.
Starting with Oracle8 i , you can use collections to improve the performance of SQL operations executed iteratively by using bulk binds. Bulk binds reduce the number of round-trips that must be made between a client application and the database. Two PL/SQL language constructs implement bulk binds: FORALL and BULK COLLECT INTO.
The syntax for the FORALL statement is:
FORALL bulk_index IN lower_bound..upper_bound sql_statement;
bulk_index can be used only in the sql_statement and only as a collection index (subscript). When PL/SQL processes this statement, the whole collection, instead of each individual collection element, is sent to the database server for processing. To delete all the accounts in the collection inactives from the table ledger, do this:
FORALL i IN inactives.FIRST..inactives.LAST DELETE FROM ledger WHERE acct_no = inactives(i);
The syntax for the BULK COLLECT INTO clause is:
BULK COLLECT INTO collection_name_list;
where collection_name_list is a comma-delimited list of collections, one for each column in the SELECT. As of Oracle8 i , collections of records cannot be a target of a BULK COLLECT INTO clause. However, 8 i does support retrieving a set of typed objects and "bulk collecting" them into a collection of objects.
The BULK COLLECT INTO clause can be used in SELECT INTO, FETCH INTO, or RETURNING INTO statements. For example:
DECLARE TYPE vendor_name_tab IS TABLE OF vendors.name%TYPE; TYPE vendor_term_tab IS TABLE OF vendors.terms%TYPE; v_names vendor_name_tab; v_terms vendor_term_tab; BEGIN SELECT name, terms BULK COLLECT INTO v_names, v_terms FROM vendors WHERE terms < 30; ... END;
The next function deletes employees in an input list of departments, and the (Oracle8) SQL RETURNING clause returns a list of deleted employees:
FUNCTION whack_emps_by_dept (deptlist dlist_t) RETURN enolist_t IS enolist enolist_t; BEGIN FORALL adept IN deptlist.FIRST..deptlist.LAST DELETE FROM emp WHERE deptno IN deptlist(adept) RETURNING empno BULK COLLECT INTO enolist; RETURN Enolist; END;
You can use the SQL%BULK_ROWCOUNT cursor attribute for bulk bind operations. It is like an index-by table containing the number of rows affected by the executions of the bulk bound statements. The n th element of SQL%BULK_ROWCOUNT contains the number of rows affected by n th execution of the SQL statement. For example:
FORALL i IN inactives.FIRST..inactives.LAST DELETE FROM ledger WHERE acct_no = inactives(i); FOR counter IN inactives.FIRST..inactives.LAST LOOP IF SQL%BULK_ROWCOUNT(counter) = 0 THEN DBMS_OUTPUT.PUT_LINE('No rows deleted for '|| counter); END IF; END LOOP;
You cannot pass SQL%BULK_ROWCOUNT as a parameter to another program, or use an aggregate assignment to another collection. %ROWCOUNT contains a summation of all %BULK_ROWCOUNT elements. %FOUND and %NOTFOUND reflect only the last execution of the SQL statement.
Copyright (c) 2000 O'Reilly & Associates. All rights reserved.