在Oracle开发中,有时我们会使用BULK COLLECT INTO批量操作大量的数据,如果没有LIMIT限制,则Oracle会读取查询的所有记录行到内存中,这样很容易造成PGA溢出而导致出现错误。所以使用LIMIT关键字可以避免PGA溢出。
示例:
SQL> DECLARE
2 TYPE typ_emp IS TABLE OF emp%ROWTYPE INDEX BY PLS_INTEGER;
3 v_emp typ_emp;
4
5 v_emp_id tab_emp_id;
6 v_total_id tab_emp_id := tab_emp_id();
7
8 v_limit NUMBER := 3;
9
10 v_test emp%ROWTYPE;
11
12 CURSOR cur_emp IS
13 SELECT * FROM emp;
14 BEGIN
15 OPEN cur_emp;
16
17 LOOP
18 FETCH cur_emp BULK COLLECT
19 INTO v_emp LIMIT v_limit;
20
21 FORALL j IN v_emp.first .. v_emp.last
22 INSERT INTO t_emp
23 VALUES
24 (seq_emp.nextval,
25 v_emp(j).ename)
26 RETURNING id BULK COLLECT INTO v_emp_id;
27
28 v_total_id := v_total_id MULTISET UNION ALL v_emp_id;
29 EXIT WHEN v_emp.count < v_limit;
30
31 END LOOP;
32
33 CLOSE cur_emp;
34
35 FOR rec IN (SELECT *
36 FROM t_emp
37 WHERE id IN (SELECT column_value FROM TABLE(v_total_id)))
38 LOOP
39 dbms_output.put_line(rec.id || '---------->' || rec.name);
40 END LOOP;
41
42 COMMIT;
43
44 END;
45 /
86---------->SMITH_甯
87---------->ALLEN
88---------->WARD
89---------->JONES
90---------->MARTIN
91---------->BLAKE
92---------->CLARK
93---------->SCOTT
94---------->KING
95---------->TURNER
96---------->ADAMS
97---------->JAMES
98---------->FORD
99---------->MILLER
PL/SQL procedure successfully completed.
SQL>