PL12 Collections
PL12 Collections
PL/SQL Collections
• A collection is an ordered group of elements, all of the
same type.
• It is a general concept that encompasses lists, arrays,
and other datatypes used in classic
programming algorithms.
• Each element is identified by a unique subscript that
represents its position in the collection.
• PL/SQL provides three collection types:
– Index-by tables or Associative array
– Nested table
– Variable-size array or Varray
Collections types
• Associative arrays, also known as index-by tables, let you
look up elements using arbitrary numbers and strings for
subscript values. These are similar to hash tables in other
programming languages.
• Nested tables hold an arbitrary number of elements. They
use sequential numbers as subscripts. You can define
equivalent SQL types, allowing nested tables to be stored in
database tables and manipulated through SQL.
• Varrays (short for variable-size arrays) hold a fixed number
of elements (although you can change the number of
elements at runtime). They use sequential numbers as
subscripts. You can define equivalent SQL types, allowing
varrays to be stored in database tables. They can be stored
and retrieved through SQL, but with less flexibility than
nested tables.
Index-By Table
• An index-by table (also called an associative
array) is a set of key-value pairs. Each key is
unique and is used to locate the corresponding
value. The key can be either an integer or a string.
• An index-by table is created using the following
syntax :
– TYPE type_name IS TABLE OF element_type [NOT
NULL] INDEX BY subscript_type;
– table_name type_name;
Example
DECLARE
TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20);
salary_list salary;
name VARCHAR2(20);
BEGIN
-- adding elements to the table
salary_list('Rajnish') := 62000;
salary_list('Minakshi') := 75000;
salary_list('Martin') := 100000;
salary_list('James') := 78000;
-- printing the table
name := salary_list.FIRST;
WHILE name IS NOT null LOOP
dbms_output.put_line
('Salary of ' || name || ' is ' || TO_CHAR(salary_list(name)));
name := salary_list.NEXT(name);
END LOOP;
END ;
/
Example
• Elements of an index-by table could also be a %ROWTYPE of any database table or
%TYPE of any database table field.
DECLARE
CURSOR c_customers is
select name from customers;
TYPE c_list IS TABLE of customers.name%type INDEX BY binary_integer;
name_list c_list;
counter integer :=0;
BEGIN
FOR n IN c_customers LOOP
counter := counter +1;
name_list(counter) := n.name;
dbms_output.put_line('Customer('||counter|| '):'||name_list(counter));
END LOOP;
END;
/
Nested Tables
• A nested table is like a one-dimensional array with an
arbitrary number of elements. However, a nested table
differs from an array in the following aspects :