Search code examples
oracle-databaseplsqlnested-table

how to insert into nested table collection using cursor plsql


I'm writing a function that needs to manipulate multiple rows at the same time and they need to be indexed. After several hours of reading about Oracle pl/sql I figured I could create a nested table kind of collection. Since I couldn't find a definitive answer and trial/error method takes way to long. Here is question part: QUESTION: What is the best practice to populate a nested table collection? Oracle PL/SQL

       type partsTable is table of Parts_north_wing%rowtype;
       pt PartsTable;    
       index number;         
       cursor pCursor is select * from Parts_north_wing;
begin
        index := 1;
        open pCursor;
        loop
                fetch pCursor into tempRow;
                pt(index) := tempRow;
                index := index + 1;
                exit when pCursor%notfound;
        end loop;
        close pCursor;

Solution

  • A cursor FOR LOOP is almost always the best way to process rows in PL/SQL. It's simpler than the OPEN/FETCH/CLOSE method - no need to declare variables and manipulate cursors. It's also faster since it automatically bulk collects the results.

    begin
        for pt in
        (
            select parts_north_wing.*, rownum row_index
            from parts_north_wing
        ) loop
            --Do something here
            null;
        end loop;
    end;
    /