Usage of nested tables in package

2025/2/18 Oracle

To temporarily store query data within Oracle packages, you can use PL/SQL collections such as associative arrays, nested tables, or VARRAYs. Here is an example using nested tables:

  1. Create the Package Specification:
CREATE OR REPLACE PACKAGE temp_data_pkg AS
    TYPE temp_table_type IS TABLE OF source_table%ROWTYPE;
    PROCEDURE populate_temp_table;
    PROCEDURE process_temp_table;
END temp_data_pkg;
1
2
3
4
5
  1. Create the Package Body:
CREATE OR REPLACE PACKAGE BODY temp_data_pkg AS
    temp_table temp_table_type;

    PROCEDURE populate_temp_table AS
    BEGIN
        -- Initialize the collection
        temp_table := temp_table_type();

        -- Populate the collection with data from the query
        SELECT * BULK COLLECT INTO temp_table
        FROM source_table
        WHERE some_condition;
    END populate_temp_table;

    PROCEDURE process_temp_table AS
    BEGIN
        -- Process each row in the collection
        FOR i IN 1 .. temp_table.COUNT LOOP
            DBMS_OUTPUT.PUT_LINE('ID: ' || temp_table(i).id || ', Name: ' || temp_table(i).name);
        END LOOP;
    END process_temp_table;
END temp_data_pkg;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  1. Execute the Procedures from the Package:
BEGIN
    temp_data_pkg.populate_temp_table;
    temp_data_pkg.process_temp_table;
END;
1
2
3
4

In this example:

  • A nested table type temp_table_type is defined in the package specification to store rows from the source_table.
  • The populate_temp_table procedure populates the nested table with data using the BULK COLLECT clause.
  • The process_temp_table procedure processes each row in the nested table.
  • The nested table temp_table is declared in the package body to store the temporary data.

This approach allows you to temporarily store and process query data within an Oracle package without creating a physical temporary table.