Function return sys_refcursor call from sql with specific columns

你说的曾经没有我的故事 提交于 2019-11-28 02:06:29

No, not with a ref cursor at all, and otherwise not without creating SQL types to cast the return into, like this example: http://dbaspot.com/oracle-server/9308-select-ref-cursor.html:

create or replace type myType as object (
a int,
b varchar2(10)
)
/

create or replace type myTable as table of myType;
/

create or replace function f1 return myTable as
l_data myTable := myTable();
begin
for i in 1 .. 5 loop
l_data.extend;
l_data(i) := myType(i, 'Row #'||i );
end loop;
return l_data;
end;
/

select * from TABLE ( cast( f1() as myTable ) );

---------- ----------
1 Row #1
2 Row #2
3 Row #3
4 Row #4
5 Row #5

From the last post on that thread:

the way you already knew about is the only one to use the REF CURSOR in a select statement.

For that purpose, you might want to take a look at PIPELINED functions. You will have to declare explicit type at PL/SQL level though. That part will set the output column name:

CREATE OR REPLACE TYPE my_rec AS OBJECT (
  c CHAR,
  n NUMBER(1)
);

CREATE OR REPLACE TYPE my_tbl AS TABLE OF my_rec;

Now, the great advantage is you can not only "rename" your columns, but modify the records from your cursor on the fly too. For ex:

CREATE OR REPLACE FUNCTION my_fct
RETURN my_tbl PIPELINED
AS
  -- dummy data - use your own cursor here
  CURSOR data IS
      SELECT 'a' as A, 1 AS B FROM DUAL UNION 
      SELECT 'b', 2 FROM DUAL UNION 
      SELECT 'c', 3 FROM DUAL UNION 
      SELECT 'd', 4 FROM DUAL;
BEGIN
  FOR the_row IN data
  LOOP 
      PIPE ROW(my_rec(the_row.a, the_row.b*2));
      --                                  ^^
      --                            Change data on the fly
  END LOOP;
END

Usage:

SELECT * FROM TABLE(my_fct())
--            ^^^^^^^^^^^^^^^
--     Use this "virtual" table like any
--     other table. Supporting `WHERE`  clause
--     or any other SELECT clause you want

Producing:

C   N
a   2
b   4
c   6
d   8
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!