Bulk-Fetching from a Cursor

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • debasisdas
    Recognized Expert Expert
    • Dec 2006
    • 8119

    Bulk-Fetching from a Cursor

    We can fetch from a cursor into one or more collections:

    [code=oracle]
    DECLARE
    TYPE NameList IS TABLE OF employees.last_ name%TYPE;
    TYPE SalList IS TABLE OF employees.salar y%TYPE;
    CURSOR c1 IS SELECT last_name, salary FROM employees WHERE salary > 10000;
    names NameList;
    sals SalList;
    TYPE RecList IS TABLE OF c1%ROWTYPE;
    recs RecList;
    PROCEDURE print_results IS
    BEGIN
    dbms_output.put _line('Results: ');
    IF names IS NULL OR names.COUNT = 0 THEN
    RETURN; -- Don't print anything if collections are empty.
    END IF;
    FOR i IN names.FIRST .. names.LAST
    LOOP
    dbms_output.put _line(' Employee ' || names(i) || ': $' ||
    sals(i));
    END LOOP;
    END;
    BEGIN
    dbms_output.put _line('--- Processing all results at once ---');
    OPEN c1;
    FETCH c1 BULK COLLECT INTO names, sals;
    CLOSE c1;
    print_results;
    dbms_output.put _line('--- Processing 7 rows at a time ---');
    OPEN c1;
    LOOP
    --LIMIT restricts the number of records to fetch.
    FETCH c1 BULK COLLECT INTO names, sals LIMIT 7;
    EXIT WHEN c1%NOTFOUND;
    print_results;
    END LOOP;
    -- Loop exits when fewer than 7 rows are fetched. Have to
    -- process the last few. Need extra checking inside PRINT_RESULTS
    -- in case it is called when the collection is empty.
    print_results;
    CLOSE c1;
    dbms_output.put _line('--- Fetching records rather than columns ---');
    OPEN c1;
    FETCH c1 BULK COLLECT INTO recs;
    FOR i IN recs.FIRST .. recs.LAST
    LOOP
    -- Now all the columns from the result set come from a single record.
    dbms_output.put _line(' Employee ' || recs(i).last_na me || ': $'
    || recs(i).salary) ;
    END LOOP;
    END;[/code]
Working...