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

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...

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;
/

How to build a dynamic PLSQL query to fetch records?

I am trying to create a stored procedure in Oracle and make a dynamic query work to get a bunch of records. I have read many examples but so far I can't get this to work unless I do this:
CREATE OR REPLACE PROCEDURE GiveMeResultSet(
v_par1 IN CHAR,
v_par2 IN CHAR,
v_par3 IN CHAR,
v_par4 IN VARCHAR2,
v_par5 IN VARCHAR2,
v_par6 IN VARCHAR2,
cur_typ OUT SYS_REFCURSOR)
IS
BEGIN
OPEN cur_typ FOR 'select * from complex_query';
--CLOSE cur_typ;
END;
And I am executing it this way:
var c refcursor;
execute GiveMeResultSet(null,null,null,null,null,null,:c);
print c;
This way I get the header names and the records from the query, but I am not closing the cursor that is fetching the results. If I close it then I get nothing at all. I guess leaving it open could cause some kind of memory leak problem at some point.
I have seen similar cases in Oracle documentation where they do something like this:
sql_stmt := 'SELECT * FROM emp';
OPEN emp_cv FOR sql_stmt;
LOOP
FETCH emp_cv INTO emp_rec;
EXIT WHEN emp_cv%NOTFOUND;
-- process record
END LOOP;
CLOSE emp_cv;
But I have no clue what goes on the "process record" part of the code which would allow to get the whole set of records at the end, plus that my record has a complex structure that doesn't fit with a fixed set of fields as in a table.
Can you please show me the proper way to do this?.
Thanks a lot.
ok CodeRoller, here is my sample code for a unspecified ref cursor:
Code of the Function which returns the ref cursor:
create or replace function test_ref_cursor(pi_sql_statement in varchar2) return SYS_REFCURSOR is
result_cursor SYS_REFCURSOR;
begin
open result_cursor for pi_sql_statement;
return result_cursor;
end;
Now, in the next step I use this function to get data from v$parameter:
declare
type t_my_cursor is ref cursor;
my_cursor t_my_cursor;
l_rec v$parameter%rowtype;
begin
my_cursor := test_ref_cursor('select * from v$parameter');
loop
fetch my_cursor into l_rec;
exit when my_cursor%notfound;
dbms_output.put_line(l_rec.name || ' = ' || l_rec.value);
end loop;
close my_cursor;
end;
Take care, to close the ref-cursor!

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.

Oracle - open a sys_refcursor for an explicit cursor

I have a function that returns a sys_refcursor so that a Java application can process the results:
function fn_stuff (in_array in t_id_array) return sys_refcursor is
rc sys_refcursor;
begin
open rc for
--query has been significantly shortened since most details are not
--relevant for this question.
select * from some_table where id in table(in_array);
return rc;
end;
I'd also like to be able to use this function with PL/SQL. It would be very convenient to be able to reference the rowtype of this result like this:
procedure sp_f is
rc sys_refcursor;
arr t_id_array ;
r c_stuff%rowtype;
begin
arr := t_id_array('11','22','33','44');
rc := pkg_stuff.fn_stuff(arr);
loop
fetch rc into r
exit when rc%notfound;
dbms_output.put_line(r.col1||' '||r.col2);
end loop;
end;
To do this, I'd need to declare the SELECT statement in fn_stuff as a proper cursor:
cursor c_stuff (in_array in t_id_array) is
select * from some_table where id in table(in_array);
So then I thought to update the function to simply reference the new cursor I declared:
function fn_stuff (in_array in t_id_array) return sys_refcursor is
rc sys_refcursor;
begin
open rc for
select * from c_stuff(in_array);
return rc;
end;
Which yields:
Error(52,37): PL/SQL: ORA-00904: : invalid identifier
I could keep the SELECT statement as it was inside fn_stuff but it's still in development so it would be easier to just have the query in a single place.
Is there any way to open and return a sys_refcursor on a declared cursor?
I guess another option is that I could declare a record type which has all of the columns that are selected by the query, but since the query is still under development and columns may be added ore removed from the select, the record type would have to be kept in sync. But since the sp_f procedure only is interested in a handful of columns that probably won't change, I thought the %rowtype would be better.

PLSQL functions in packages query

I am having a table named employees..i want to write two functions.1st function by using refcursor it want to fetch all the rows from employess table...and the result wil be shown through 2nd function.These two functions should be in one single package
Your question shows very little industry or effort to work out a solution.
Start by reading the Oracle documentation and it'll help you immensely.
As an example of what you want to achieve:
CREATE OR REPLACE
PACKAGE ref_cur_package
AS
FUNCTION get_emp
RETURN SYS_REFCURSOR;
PROCEDURE show_emp;
END ref_cur_package;
CREATE OR REPLACE
PACKAGE BODY ref_cur_package
AS
FUNCTION get_emp
RETURN SYS_REFCURSOR
IS
emp_rc SYS_REFCURSOR;
BEGIN
OPEN emp_rc
FOR SELECT *
FROM emp;
RETURN emp_rc;
END get_emp;
PROCEDURE show_emp
IS
emp_rc SYS_REFCURSOR;
emp_row emp%ROWTYPE;
BEGIN
emp_rc := get_emp;
LOOP
FETCH emp_rc INTO emp_row;
EXIT WHEN emp_rc%NOTFOUND;
DBMS_OUTPUT.put_line('Employee: '||emp_row.firstname||' '||emp_row.lastname);
END LOOP;
CLOSE emp_rc;
END show_emp;
END ref_cur_package;
/
To see the output you'll need to set the serveroutput on.
You should also add an exception handler to force the closure of the ref cursor if there is a problem but I will leave that to you to research.

Resources