09.01.2015 Views

PL/SQL User's Guide and Reference

PL/SQL User's Guide and Reference

PL/SQL User's Guide and Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Retrieving Query Results into Collections with the BULK COLLECT Clause<br />

In the next example, the <strong>SQL</strong> engine loads all the values in an object column into a<br />

nested table before returning the table to the <strong>PL</strong>/<strong>SQL</strong> engine:<br />

CREATE TYPE Coords AS OBJECT (x NUMBER, y NUMBER);<br />

CREATE TABLE grid (num NUMBER, loc Coords);<br />

INSERT INTO grid VALUES(10, Coords(1,2));<br />

INSERT INTO grid VALUES(20, Coords(3,4));<br />

DECLARE<br />

TYPE CoordsTab IS TABLE OF Coords;<br />

pairs CoordsTab;<br />

BEGIN<br />

SELECT loc BULK COLLECT INTO pairs FROM grid;<br />

-- now pairs contains (1,2) <strong>and</strong> (3,4)<br />

END;<br />

The <strong>SQL</strong> engine initializes <strong>and</strong> extends collections for you. (However, it cannot<br />

extend varrays beyond their maximum size.) Then, starting at index 1, it inserts<br />

elements consecutively <strong>and</strong> overwrites any pre-existent elements.<br />

The <strong>SQL</strong> engine bulk-binds entire database columns. So, if a table has 50,000 rows,<br />

the engine loads 50,000 column values into the target collection. However, you can<br />

use the pseudocolumn ROWNUM to limit the number of rows processed. In the<br />

following example, you limit the number of rows to 100:<br />

DECLARE<br />

TYPE SalList IS TABLE OF emp.sal%TYPE;<br />

sals SalList;<br />

BEGIN<br />

SELECT sal BULK COLLECT INTO sals FROM emp<br />

WHERE ROWNUM 1000;<br />

names NameList;<br />

<strong>PL</strong>/<strong>SQL</strong> Collections <strong>and</strong> Records 5-47

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!