Search code examples
sqlfunctionsql-types

Why the table of my function is not acceptable?


CREATE OR REPLACE
PACKAGE PKG
AS
TYPE RESULT_T
IS
  TABLE OF VARCHAR2(3000);
FUNCTION GENERATEF
  RETURN RESULT_T ;
END PKG;
/
CREATE OR REPLACE
PACKAGE BODY PKG
AS
FUNCTION GENERATEF
  RETURN RESULT_T
IS
  i_t RESULT_T := RESULT_T();
BEGIN

  FOR TLC IN 1..3
  LOOP
    i_t.extend;
    i_t(i_t.last) := tlc;
  END LOOP;
  RETURN i_t;
END;
END PKG;
/

When I want to execute "select * from table(pkg.GENERATEF);", the system tells me there is an "invalid datatype". I'm not sure what brings the issue.


Solution

  • This type RESULT_T is not globally defined, so that's why Oracle (or any DBMS) could not identify this type and so is not able to cast the output as Table form.

    You can specify this type outside the package as -

    Create or Replace TYPE RESULT_T IS
      TABLE OF VARCHAR2(3000);
    

    and then remove the definition for this type from your package as -

    CREATE OR REPLACE PACKAGE Pkg AS
      /*TYPE RESULT_T
      IS
        TABLE OF VARCHAR2(3000);*/
      FUNCTION Generatef RETURN Result_t;
    END Pkg;
    /
    CREATE OR REPLACE PACKAGE BODY Pkg AS
      FUNCTION Generatef RETURN Result_t IS
        i_t Result_t := Result_t();
      BEGIN
    
        FOR Tlc IN 1 .. 3 LOOP
          i_t.EXTEND;
          i_t(i_t.LAST) := Tlc;
        END LOOP;
        RETURN i_t;
      END;
    END Pkg;
    /
    

    and then when you will query for -

    select * from table(pkg.GENERATEF); you will get the result as desired.