Using same pipelined function several times in the same query - oracle

I'm trying to write a pipelined function which uses another pipelined function several times.
So, function context_Set receives a cursor and returns results that should be used several times in pipelined funcion m0 which also receives a cursor as an argument (the sql logic is simplified to UNION):
create or replace PACKAGE BODY PKG_PIPE AS
FUNCTION context_Set(l_res sys_refcursor)
RETURN resulting_cols_rt PIPELINED
IS
recs resulting_record_rt;
BEGIN
loop
fetch l_res into recs;
exit when l_res%notfound;
PIPE ROW(recs);
end loop;
close l_res;
return;
END context_Set;
-------------------- BEGIN: 01.TEST ---------------------
FUNCTION m0(l_res sys_refcursor)
RETURN resulting_cols_rt PIPELINED
IS
recs resulting_record_rt;
l_in_res SYS_REFCURSOR;
BEGIN
open l_in_res for
select resulting_record_rt(c1,c2,c3,c4) FROM (
SELECT * FROM context_Set(l_res)
UNION ALL
SELECT * FROM context_Set(l_res));
loop
fetch l_in_res into recs;
exit when l_in_res%notfound;
PIPE ROW(recs);
end loop;
close l_in_res;
return;
END m0;
END PKG_PIPE;
and the function is called like the following:
open l_res for 'select resulting_record_rt(c1,c2,c3,c4) from (select ... )';
select *
FROM PKG_PIPE.m0(l_res);
close l_res;
The error I'm getting is:
ORA-01001: invalid cursor
When UNION and the second SELECT are removed the function works fine.
Is there some way to rewrite the same to make it work?

Related

PL/SQL Function - Bulk Collect into and Pipe Row

I am new to PL/SQL have issue with output value of a function.
I want to execute a SQL statement in a function and return the results. The function will be executed with following command: select * from table(mypkg.execute_query('1'));
I was using following article as refence "Bulk Collect Into" and "Execute Immediate" in Oracle, but without success.
It seems that I am using wrong data type. System returns issue on following line: PIPE Row(results)
create or replace package mypkg
as
type node is table of edges%ROWTYPE;
function execute_query (startNode in varchar2) RETURN node PIPELINED;
end;
create or replace package body mypkg
as
function execute_query(startNode in varchar2) RETURN node PIPELINED
AS
results node;
my_query VARCHAR2(100);
output VARCHAR2(1000);
c sys_refcursor;
BEGIN
my_query := 'SELECT DISTINCT * FROM EDGES WHERE src='|| startNode;
open c for my_query;
loop
fetch c bulk collect into results limit 100;
exit when c%notfound;
PIPE Row(results);
end loop;
close c;
END;
end;
I tried several options with cursor but wasn't able to return the value. If you have idea how to return the data by using something else than PIPELINED, please let me know.
Thanks for your support!
Fixed body:
create or replace package body mypkg
as
function execute_query(startNode in varchar2) RETURN node PIPELINED
AS
results node;
my_query VARCHAR2(100);
output VARCHAR2(1000);
c sys_refcursor;
BEGIN -- don't use concatenation, it leads to sql injections:
my_query := 'SELECT DISTINCT * FROM EDGES WHERE src=:startNode';
-- use bind variables and bind them using cluase "using":
open c for my_query using startNode;
loop
fetch c bulk collect into results limit 100;
-- "results" is a collection, so you need to iterate it to pipe rows:
for i in 1..results.count loop
PIPE Row(results(i));
end loop;
exit when c%notfound;
end loop;
close c;
END;
end;
/

standalone pipelined function calling another standalone pipelined function

I want to write two pipelined functions, standalone, meaning outside of PL/SQL package:
create or replace function fn_test_1
return sys.DBMS_DEBUG_VC2COLL pipelined -- ODCIVARCHAR2LIST
AS
BEGIN
FOR l_row in ( ... )
LOOP
PIPE ROW('text');
PIPE ROW('other text');
PIPE ROW(strings_concatenated);
END LOOP;
END;
/
create or replace function fn_test_2
return sys.DBMS_DEBUG_VC2COLL pipelined -- ODCIVARCHAR2LIST
AS
BEGIN
FOR l_row in ( select column_value as line from TABLE( fn_test_1 ) )
LOOP
PIPE ROW(l_row);
END LOOP;
END;
/
fn_test_1 compiles successfully and works fine. However I cannot compile fn_test_2 becuase of:
PLS-00382: expression is of wrong type
Can I even write standalone pipelined functions one calling the other?
You're return a cursor and not the value it has, use this:
create or replace function fn_test_2
return sys.DBMS_DEBUG_VC2COLL pipelined -- ODCIVARCHAR2LIST
AS
BEGIN
FOR l_row in ( select column_value as line from TABLE( fn_test_1 ) )
LOOP
PIPE ROW(l_row.line);
END LOOP;
END;
/

Function to return a cursor in PL SQL,

I have a function which returns a SYS_REFCURSOR, this function is to be called from different packages and we don't want to have to duplicate the cursor definition in multiple places.
FUNCTION f_get_cur(p_date DATE, p_code VARCHAR(10)) RETURN SYS_REFCURSOR IS
cur_s SYS_REFCURSOR;
BEGIN
OPEN cur_s FOR
SELECT .blah blah etc etc
return cur_s;
END f_get_cur;
Which compiles ok, however when I want to use the function in a FOR LOOP where I'd normally put the cursor I get the following error
Error: PLS-00456: item 'f_get_cur' is not a cursor
I'm attempting to open the cursor like so...
FOR cc_rec IN f_get_cur(c_date, p_c_code) LOOP
Am I using the wrong data type? Is there some other way of achieving what I'm trying?
You need to handle the returned cursor in a different way; for example:
SQL> create or replace FUNCTION f_get_cur(p_date DATE, p_code VARCHAR) RETURN SYS_REFCURSOR IS
2 cur_s SYS_REFCURSOR;
3 BEGIN
4 OPEN cur_s FOR
5 SELECT to_char(p_date, 'dd-mm-yyyy') || p_code val from dual;
6
7 return cur_s;
8 END f_get_cur;
9 /
Function created.
SQL> declare
2 cur_s SYS_REFCURSOR;
3 v varchar2(100);
4 begin
5 cur_s := f_get_cur(sysdate, 'xx');
6 loop
7 fetch cur_s into v;
8 exit when cur_s%NOTFOUND;
9 dbms_output.put_line(v);
10 end loop;
11 end;
12 /
30-04-2019xx
PL/SQL procedure successfully completed.
SQL>
I managed to get this working by creating another(!) cursor which implements the function I already created (which wraps the original cursor)
cursor cur_real(cp_date DATE, cd_code VARCHAR2(10)) IS
select ... etc
FROM TABLE(f_get_cur(cp_date, cp_code));
I can now use the cursor like so
FOR cc_rec IN f_get_cur(c_date, p_c_code) LOOP
do stuff ... etc
END LOOP

Tail call for pipelined functions

I have some pipelined function:
create type my_tab_type as table of ...
create function my_func (X in number) return my_tab_type pipelined as
begin
loop
...
pipe row (...);
end loop;
return;
end;
Now I want to create another pipelined function my_func_zero which does the same as my_func but for fixed value of parameter: my_func_zero must be equivalent to my_func(0).
Can I implement my_func_zero without senseless and boring loop for processing every row returned by select * from table(my_func(0))?
P.S. That thread is a bit similar, but it does not contain answer to my question.
It's possible, but only if you don't declare your second function as pipelined because all functions of this type return results on row-by-row basis.
If you omit this requirement you can reach your target with bulk collect if you need typed cursor:
create function my_zero_func return my_tab_type
as
res_table my_tab_type;
begin
select my_type(field1, field2)
bulk collect into res_table
from table(my_func(0));
return res_table;
end;
Alternatively you can use untyped cursor:
create function my_ref_zero_func return sys_refcursor
as
vRes sys_refcursor;
begin
open vRes for select * from table(my_func(0));
return vRes;
end;
SQLFiddle
In a client application my_ref_zero_func results may be used without changes, but in the SQLFiddle it converted to XML representation because there are no way to demonstrate ref cursor with this tool.

What is the standard way to return records from an Oracle function?

I really avoided the "best" word for my question but it really is the most suitable word for it.
What's the best(most efficient) way of returning records from a function?
Currently I have something like:
FUNCTION myFunct(param1 VARCHAR2) RETURN SYS_REFCURSOR AS
myCursor SYS_REFCURSOR;
BEGIN
OPEN myCursor FOR
SELECT *
FROM myTable
WHERE field = param1;
RETURN(myCursor);
END myFunct;
I can run this fine but with everything else I am reading like (TABLE type, implicit cursor, etc) I am really confused about what is most suitable.
P.S. how can I loop over this cursor after I call it from a proc?
EDIT:
I've read that I can only iterate through cursors ONCE (forums.oracle.com/thread/888365) but in reality I want to loop contents several times. Does this mean that I am opt to use associative arrays instead?
create or replace
PACKAGE example_pkg AS
/*
** Record and nested table for "dual" table
** It is global, you can use it in other packages
*/
TYPE g_dual_ntt IS TABLE OF SYS.DUAL%ROWTYPE;
g_dual g_dual_ntt;
/*
** procedure is public. You may want to use it in different parts of your code
*/
FUNCTION myFunct(param1 VARCHAR2) RETURN SYS_REFCURSOR;
/*
** Example to work with a cursor
*/
PROCEDURE example_prc;
END example_pkg;
create or replace
PACKAGE BODY example_pkg AS
FUNCTION myFunct(param1 VARCHAR2) RETURN SYS_REFCURSOR
AS
myCursor SYS_REFCURSOR;
BEGIN
OPEN myCursor FOR
SELECT dummy
FROM dual
WHERE dummy = param1;
RETURN(myCursor);
END myFunct;
PROCEDURE example_prc
AS
myCursor SYS_REFCURSOR;
l_dual g_dual_ntt; /* With bulk collect there is no need to initialize the collection */
BEGIN
-- Open cursor
myCursor := myFunct('X');
-- Fetch from cursor / all at onece
FETCH myCursor BULK COLLECT INTO l_dual;
-- Close cursor
CLOSE myCursor;
DBMS_OUTPUT.PUT_LINE('Print: ');
FOR indx IN 1..l_dual.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('element: ' || l_dual(indx).dummy );
END LOOP;
END example_prc;
END example_pkg;
EXECUTE example_pkg.example_prc();
/*
Print:
element: X
*/
Please take a look at this link: http://www.oracle-base.com/articles/misc/using-ref-cursors-to-return-recordsets.php
You might find it useful...

Resources