简体   繁体   中英

Oracle / function that may return two different types

I have a pipelined table function that return a collection of types :

create or replace FUNCTION test(A varchar2 )
 RETURN type_As PIPELINED  as row_type type_A;
Begin
...
select type_A(...) 
  into   row_type 
  from   dual;
PIPE ROW(row_type);
  return ;
end;

I created a new type type_B and collection type_Bs. what I need is to return type_As or type_Bs based on condition inside the function.

the issue is that I cannot use two functions as I have an application that have to call one function regardless of the output.

can I create a function that call one of the 2 functions based on certain condition and still keep the output ?

any help will be appreciated

How about returning a ref cursor? Have a look:

SQL> create or replace function p_test (par_tab in varchar2)
  2    return sys_refcursor
  3  is
  4    lc sys_refcursor;
  5  begin
  6    if    par_tab = 'D' then
  7      open lc for select deptno, dname, loc from dept;
  8    elsif par_tab = 'E' then
  9      open lc for select empno, ename, sal from emp;
 10    end if;
 11
 12    return lc;
 13  end;
 14  /

Function created.

SQL>

Let's test it:

SQL> select p_test('E') from dual;

P_TEST('E')
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

     EMPNO ENAME             SAL
---------- ---------- ----------
      7839 KING             5000
      7698 BLAKE            2850
      7782 CLARK            2450
      7566 JONES            2975
      7788 SCOTT            3000
      7902 FORD             3000
      7369 SMITH             800
      7499 ALLEN            1600
      7521 WARD             1250
      7654 MARTIN           1250
      7844 TURNER           1500
      7876 ADAMS            1100
      7900 JAMES             950
      7934 MILLER           1300

14 rows selected.

Another one:

SQL> select p_test('D') from dual;

P_TEST('D')
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON


SQL>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM