Associative arrays v15
An associative array is a type of collection that associates a unique key with a value. The key doesn't have to be numeric. It can be character data as well.
An associative array has the following characteristics:
- You must define an associative array type after which you can declare array variables of that array type. Data manipulation occurs using the array variable.
- When an array variable is declared, the associative array is created, but it is empty. Start assigning values to key values.
- The key can be any negative integer, positive integer, or zero if you specify
INDEX BY BINARY_INTEGER
orPLS_INTEGER
. - The key can be character data if you specify
INDEX BY VARCHAR2
. - There's no predefined limit on the number of elements in the array. It grows dynamically as elements are added.
- The array can be sparse. There can be gaps in the assignment of values to keys.
- An attempt to reference an array element that hasn't been assigned a value results in an exception.
The TYPE IS TABLE OF ... INDEX BY
statement is used to define an associative array type:
Where:
assoctype
is an identifier assigned to the array type.
datatype
is a scalar data type such as VARCHAR2
or NUMBER
.
rectype
is a previously defined record type.
objtype
is a previously defined object type.
n
is the maximum length of a character key.
To make use of the array, you must declare a variable with that array type. The following is the syntax for declaring an array variable:
Where:
array
is an identifier assigned to the associative array.
assoctype
is the identifier of a previously defined array type.
Reference an element of the array using the following syntax:
array
is the identifier of a previously declared array.
n
is the key value, type-compatible with the data type given in the INDEX BY
clause.
If the array type of array
is defined from a record type or object type, then [.field ]
must reference an individual field in the record type or attribute in the object type from which the array type is defined. Alternatively, you can reference the entire record by omitting [.field ]
.
This example reads the first 10 employee names from the emp
table, stores them in an array, and then displays the results from the array:
This example produces the following output:
This example uses a record type in the array definition:
The following is the output from this anonymous block:
This example uses the emp%ROWTYPE
attribute to define emp_arr_typ
instead of using the emp_rec_typ
record type:
The results are the same as using a record type in the array definition.
Instead of assigning each field of the record individually, you can make a record-level assignment from r_emp
to emp_arr
:
This example uses the key of an associative array as character data: