Use the BULK COLLECT feature when you need to fetch large amounts of data. This will increase the speed of excution of the pl/sql but consume more memory. The amount of memory consumed can be controlled through the LIMIT clause.
Below is an example that fetches all the rows at once.
declare
TYPE v_codes_type
IS TABLE OF v_codes%ROWTYPE
INDEX BY PLS_INTEGER;
l_code v_codes_type; --You can also use a view/cursor instead of a table
BEGIN
SELECT *
BULK COLLECT INTO l_code
FROM v_codes;
FOR indx IN 1 .. l_code.COUNT --indx variable need not be declared
LOOP
dbms_output.put_line('Code_id ' || l_code(indx).code_id || 'code_type '|| l_code(indx).code_type);
--use of l_code(indx) like a structure to display the values
END LOOP;
END;
/
Rather than fetching all the rows and consuming memory you can use the LIMIT clause.
You need to utilise a cursor to use the LIMIT clause.
Below is an example with LIMIT clause
declare
cursor v_codes_cur is
select * from v_codes;
TYPE v_codes_type IS TABLE OF v_codes_cur%ROWTYPE
INDEX BY PLS_INTEGER;
l_code v_codes_type;
BEGIN
Open v_codes_cur;
LOOP
FETCH v_codes_cur
BULK COLLECT into l_code LIMIT 100;
FOR indx IN 1 .. l_code.COUNT LOOP
dbms_output.put_line('Code_id ' || l_code(indx).code_id || 'code_type ' || l_code(indx).code_type);
END LOOP;
EXIT WHEN 1_code.count =0 ;
END LOOP;
close v_codes_cur;
END;
/
According to an article by Steve the performance doesn't improve much when the limit clause is more than 25.The performance pretty much remains the same for a limit clause value more than 25.
Note: Use of %NOTFOUND with BULK COLLECT
Don't use %NOTFOUND with BULK COLLECT because some of the rows will not get selected.
Instead use the
EXIT WHEN l_code.COUNT=0 value to determine if all the rows have been selected.
The EXIT WHEN v_codes_cur%NOTFOUND is suitable when fetching a single row at a time.
Here are a few important points on BULK COLLECT.
1) The collection is filled sequentially starting with index 1
2) The collection is empty when no data is selected.
3) Always check the contents of collection with the COUNT to see if any rows are selected.
4) Ignore the other cursor attrributes like %NOTFOUNd when using BULK COLLECT.
The program above was written in PL/SQL.
ReplyDeleteThe big question is:
"How do you translate that code into Pro*C ?"
I suppose you would use an array of structs instead of the table.
Thank you.