2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
A ``++FETCH ... BULK COLLECT INTO++`` without a ``++LIMIT++`` clause will load all the records returned by the cursor at once. This may lead to memory exhaustion. Instead, it is better to process the records in chunks using the ``++LIMIT++`` clause.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-04-28 16:49:39 +02:00
----
SET SERVEROUTPUT ON
-- Fetches all records at once, requiring lots of memory
DECLARE
TYPE largeTableRowArrayType IS TABLE OF largeTable%ROWTYPE;
largeTableRowArray largeTableRowArrayType;
CURSOR myCursor IS SELECT * FROM largeTable;
BEGIN
OPEN myCursor;
FETCH myCursor BULK COLLECT INTO largeTableRowArray; -- Non-compliant
DBMS_OUTPUT.PUT_LINE('Alternative 1: ' || largeTableRowArray.COUNT || ' records');
CLOSE myCursor;
END;
/
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-04-28 16:49:39 +02:00
----
SET SERVEROUTPUT ON
-- fetches one chunk at a time, requiring constant memory
DECLARE
TYPE largeTableRowArrayType IS TABLE OF largeTable%ROWTYPE;
largeTableRowArray largeTableRowArrayType;
CURSOR myCursor IS SELECT * FROM largeTable;
counter PLS_INTEGER := 0;
BEGIN
OPEN myCursor;
LOOP
FETCH myCursor BULK COLLECT INTO largeTableRowArray LIMIT 1000; -- Compliant
counter := counter + largeTableRowArray.COUNT;
EXIT WHEN myCursor%NOTFOUND;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Alternative 1: ' || counter || ' records');
CLOSE myCursor;
END;
/
DROP TABLE largeTable;
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Add a "LIMIT" clause to the statement.
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]