天天看點

oracle中bulk collect into用法

通過bulk collect減少loop處理的開銷

采用bulk collect可以将查詢結果一次性地加載到collections中。

而不是通過cursor一條一條地處理。

可以在select into,fetch into,returning into語句使用bulk collect。

注意在使用bulk collect時,所有的into變量都必須是collections.

舉幾個簡單的例子:

--在select into語句中使用bulk collect

DECLARE

TYPE SalList IS TABLE OF emp.sal%TYPE;

sals SalList;

BEGIN

-- Limit the number of rows to 100.

SELECT sal BULK COLLECT INTO sals FROM emp

WHERE ROWNUM <= 100;

-- Retrieve 10% (approximately) of the rows in the table.

SELECT sal BULK COLLECT INTO sals FROM emp SAMPLE 10;

END;

/

--在fetch into中使用bulk collect

TYPE DeptRecTab IS TABLE OF dept%ROWTYPE;

dept_recs DeptRecTab;

CURSOR c1 IS

SELECT deptno, dname, loc FROM dept WHERE deptno > 10;

OPEN c1;

FETCH c1 BULK COLLECT INTO dept_recs;

--在returning into中使用bulk collect

CREATE TABLE emp2 AS SELECT * FROM employees;

TYPE NumList IS TABLE OF employees.employee_id%TYPE;

enums NumList;

TYPE NameList IS TABLE OF employees.last_name%TYPE;

names NameList;

DELETE FROM emp2 WHERE department_id = 30

RETURNING employee_id, last_name BULK COLLECT INTO enums, names;

dbms_output.put_line('Deleted ' || SQL%ROWCOUNT || ' rows:');

FOR i IN enums.FIRST .. enums.LAST

LOOP

dbms_output.put_line('Employee #' || enums(i) || ': ' || names(i));

END LOOP;

DROP TABLE emp2;