Search code examples
oracle-databaseplsqlcastingcursoruser-defined-types

PL/SQL: Cannot cast table%ROWTYPE to user-defined TYPE TABLE. But no error given


I have a Package with a user-type RECORD AND a user-type TABLE of the first type:

TYPE ObjData IS RECORD (
    Test date NOT NULL := DATE '0001-01-01',
    Val decimal
);
TYPE ObjDataCollection IS TABLE
    OF ObjData;

I need to call a PROCEDURE from the Package passing as param a ObjDataCollection object, fetched from a DBTable:

SELECT LogDate, TypeVal FROM UserLogs

When I call the query, it returns dozens of records, but nothing is returned by this function I tried:

CREATE FUNCTION TestData RETURN MyPackage.ObjDataCollection AS
  res MyPackage.ObjDataCollection;
BEGIN
  SELECT LogDate, TypeVal
    BULK COLLECT INTO res
    FROM UserLogs
    ORDER BY LogDate;
  RETURN res;
END TestData;

This is Running window Log:

Connecting to the database MYDB.
Process exited.
Disconnecting from the database MYDB.

And this is the Output Variables window (it's empty): Screenshot


Solution

  • The %ROWCOUNT attribute of a cursor tells you how many rows have been fetched so far not how many rows could be fetched. So checking the %ROWCOUNT before fetching data is a mistake. That will always return 0.

    In this case, your IF statement is unnecessary. I also wouldn't bother to define a cursor variable either, just

    CREATE FUNCTION TestData
      RETURN MyPackage.ObjDataCollection
    AS
      res MyPackage.ObjDataCollection;
    BEGIN
      SELECT LogDate, TypeVal
        BULK COLLECT INTO res
        FROM UserLogs
       ORDER BY LogDate;
    
      RETURN res;
    END;