oracleplsqlcursorbulk-collect

SELECT from a bulk collection


Is it possible to select from a bulk collection?

Something along these lines:

DECLARE
  CURSOR customer_cur IS
    SELECT CustomerId,
          CustomerName
    FROM   Customers
    WHERE  CustomerAreaCode = '576';

  TYPE customer_table IS TABLE OF customer_cur%ROWTYPE;
  my_customers  customer_table; 
BEGIN

  OPEN customer_cur;

  FETCH customer_cur
  BULK COLLECT INTO my_customers;

  -- This is what I would like to do
  SELECT CustomerName
    FROM my_customers
   WHERE CustomerId IN (1, 2, 3); 

END;

I don't seem to be able to select from the my_customers table.


Solution

  • Yes, you can. Declare yourself schema-level types as follows:

    create or replace rec_customer_cur
    as
    object (
        customerid       integer, -- change to the actual type of customers.customerid
        customername     varchar2(100) -- change to the actual type of customers.customername
    );
    /
    
    create or replace type customer_table
    as
    table of rec_customer_cur;
    /
    

    Then, in your PLSQL code, you can declare

    CURSOR customer_cur IS
    SELECT new rec_customer_cur(CustomerId, CustomerName)
    FROM   Customers
    WHERE  CustomerAreaCode = '576';
    

    ... and then use ...

    SELECT CustomerName
    INTO whatever
    FROM table(my_customers)
    WHERE CustomerId IN (1, 2, 3); 
    

    This is because schema-level types can be used in SQL context.