I want to execute a SQL query inside PL/SQL and populate the results into an associative array, where one of the columns in the SQL becomes the key in the associative array. For example, say I have a table Person
with columns
PERSON_ID INTEGER PRIMARY KEY
PERSON_NAME VARCHAR2(50)
...and values like:
PERSON_ID | PERSON_NAME
------------------------
6 | Alice
15 | Bob
1234 | Carol
I want to bulk collect this table into a TABLE OF VARCHAR2(50) INDEX BY INTEGER
such that the key 6
in this associative array has the value Alice
and so on. Can this be done in PL/SQL? If so, how?
If we want to specify the value in an associative array's index then we have to use this syntax:
We can populate associative arrays with bulk collect but only if the index is an integer, and we are happy to index by (an implicit) ROWNUM, i.e not a sparse key...
To be fair, if you need to use BULK COLLECT you are probably dealing with more data than is appropriate for an associative array.
Edit
A cheap-ish performance test of the two approaches:
Wall-clock performance tests are notoriously ropey. But for a few hundred records, any difference is unlikely to be worth worrying about, certainly in the context of the sort of place where we might want to use an assoociative array.
Edit 2
@Dan said:
It really depends on your definition of "a decent sized number". Are there really that many cases where we would want to populate an associative array with thousands of rows, with a string index? When we get to those sorts of numbers a normal database table might be just as useful, especially on 11g Enterprise Edition with resultset caching.
No, you have to use either 2 collections (id, name) or one whose element type is a record.
Here's a sample of the latter: