Thursday, June 17, 2010

Using Bulk collect in PL\SQL

I am used to using bulk collect in cursor variables. But I guess i have'nt worked on it enough to master its usage. Yesterday's question on plsqlchallenge really made me thing of them some more. I am reproducing the examples here for my reference in the future.

You can use BULK COLLECT with both implicit and explicit cursors, in both static and dynamic SQL, and with cursor variables. The following blocks demonstrate each approach.
With an explicit cursor:

DECLARE
CURSOR employees_cur IS SELECT * FROM employees;
TYPE employees_aat IS TABLE OF employees%ROWTYPE
INDEX BY BINARY_INTEGER;
l_employees employees_aat;
BEGIN
OPEN employees_cur;
FETCH employees_cur BULK COLLECT INTO l_employees;
CLOSE employees_cur;
END;

With an implicit cursor:

DECLARE
TYPE employees_aat IS TABLE OF employees%ROWTYPE
INDEX BY BINARY_INTEGER;
l_employees employees_aat;
BEGIN
SELECT * BULK COLLECT INTO l_employees FROM employees;
END;

With a dynamic SQL statement (Oracle 9i Release 2 and above):

DECLARE
TYPE employees_aat IS TABLE OF employees%ROWTYPE
INDEX BY BINARY_INTEGER;

l_employees employees_aat;
BEGIN
EXECUTE IMMEDIATE 'SELECT * FROM employees' BULK COLLECT INTO l_employees;
END;

And here's an example of using BULK COLLECT with a cursor variable:

DECLARE
l_cursor sys_refcursor;
l_list DBMS_SQL.varchar2s;
BEGIN
OPEN l_cursor FOR
SELECT last_name
FROM employees;

LOOP
FETCH l_cursor
BULK COLLECT INTO l_list
LIMIT 100;

EXIT WHEN l_list.COUNT = 0;
END LOOP;

CLOSE l_cursor;
END;

No comments: