Oracle: Select From Record Datatype

后端 未结 6 993

I have a function that returns a record datatype (2 fields: ID and Name). How can I get at the data from a select statement?

Specifically, I am trying using an Oracl

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 20:08

    A record datatype is a PL/SQL datatype. SQL doesn't know about it. That's probably why you are getting an error. See this example:

    SQL> create package mypkg
      2  as
      3    type myrec is record
      4    ( id int
      5    , name varchar2(10)
      6    );
      7    function f return myrec;
      8  end mypkg;
      9  /
    
    Package created.
    
    SQL> create package body mypkg
      2  as
      3    function f return myrec
      4    is
      5      r myrec;
      6    begin
      7      r.id := 1;
      8      r.name := 'test';
      9      return r;
     10    end f;
     11  end mypkg;
     12  /
    
    Package body created.
    
    SQL> desc mypkg
    FUNCTION F RETURNS RECORD
       ID                           NUMBER(38)              OUT
       NAME                         VARCHAR2(10)            OUT
    
    SQL> select mypkg.f from dual
      2  /
    select mypkg.f from dual
           *
    ERROR at line 1:
    ORA-00902: invalid datatype
    

    The error in SQL I was referring to. You can call it from PL/SQL though:

    SQL> declare
      2    r mypkg.myrec;
      3  begin
      4    r := mypkg.f;
      5    dbms_output.put_line(r.id);
      6    dbms_output.put_line(r.name);
      7  end;
      8  /
    1
    test
    
    PL/SQL procedure successfully completed.
    

    If you want to use the function in SQL, then you can create a SQL objecttype. Note that calling your function directly from C# looks way more preferable than insisting on using SQL to do this. But just for the record:

    SQL> drop package mypkg
      2  /
    
    Package dropped.
    
    SQL> create type myobj is object
      2  ( id int
      3  , name varchar2(10)
      4  );
      5  /
    
    Type created.
    
    SQL> create package mypkg
      2  as
      3    function f return myobj;
      4  end mypkg;
      5  /
    
    Package created.
    
    SQL> create package body mypkg
      2  as
      3    function f return myobj
      4    is
      5    begin
      6      return myobj(1,'test');
      7    end f;
      8  end mypkg;
      9  /
    
    Package body created.
    
    SQL> select mypkg.f from dual
      2  /
    
    F(ID, NAME)
    --------------------------------------------------------------
    MYOBJ(1, 'test')
    
    1 row selected.
    

    Regards, Rob.

提交回复
热议问题