Skip to content
Advertisement

Select a column from table return by function in Oracle

I have a function that returns a table of custom objects. I wish to select a certain column by name from the returned result.

create or replace type sd_Serial_Number as object (
  serial_number VARCHAR2(32)
);

The table of objects

create or replace type sd_Serial_Number_Table as table of sd_Serial_Number;

The function

create function get_result
return sd_Serial_Number_Table as
    v_ret   sd_Serial_Number_Table;

begin
    select sd_Serial_Number(selected.SERIAL_NUMBER)
           bulk collect into v_ret
    from (
        selection here
        ) selected;

    return v_ret;
end get_result;

When I call the function this way, I get a result with a single column called SERIAL_NUMBER

select * from table(get_result());

However, I can’t do something like this

select SERIAL_NUMBER from table(get_result());

Is there a way to select the column SERIAL_NUMBER ?

Advertisement

Answer

“I can’t” is difficult to debug. I’ll show you that I can (on the same database version you use).

SQL> SELECT * FROM v$version WHERE rownum = 1;

BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production

SQL> CREATE OR REPLACE TYPE sd_serial_number AS OBJECT
  2  (
  3     serial_number VARCHAR2 (32)
  4  );
  5  /

Type created.

SQL> CREATE OR REPLACE TYPE sd_serial_number_table AS TABLE OF sd_serial_number;
  2  /

Type created.

SQL> CREATE OR REPLACE FUNCTION get_result
  2     RETURN sd_serial_number_table
  3  AS
  4     v_ret  sd_serial_number_table;
  5  BEGIN
  6     SELECT sd_serial_number (deptno)
  7       BULK COLLECT INTO v_ret
  8       FROM dept;
  9
 10     RETURN v_ret;
 11  END get_result;
 12  /

Function created.

Testing:

SQL> SELECT * FROM TABLE (get_result ());

SERIAL_NUMBER
--------------------------------
10
20
30
40

SQL> SELECT serial_number FROM TABLE (get_result ());

SERIAL_NUMBER
--------------------------------
10
20
30
40

SQL>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement