principleModerate
How and when to use sys_refcursor in oracle
Viewed 0 times
sys_refcursororaclehowwhenanduse
Problem
Can some one give me a small explanation about how and when should someone use sys_refcursor ?
Solution
A cursor is a pointer to a result set for a query. By returning a
A cursor can allow more flexibility than writing a PL/SQL function that returns an array as it's completely up to the client how many rows to fetch and when to stop. That said, I've not found many cases where this additional flexibility is useful.
It's worth noting that the
This enables you to write functions which return different queries, like so:
However, if you're using
sys_refcursor you allow the client to fetch as many or few of the rows from the query as it requires. In stateful applications this could be used to page through results. A cursor can allow more flexibility than writing a PL/SQL function that returns an array as it's completely up to the client how many rows to fetch and when to stop. That said, I've not found many cases where this additional flexibility is useful.
It's worth noting that the
sys_refcursor is weakly typed, so you can return pointers to queries which not only have different from or where clauses, but different numbers and types of columns as well. Alternatively you can use strongly typed cursor where the columns in the result set are fixed. This enables you to write functions which return different queries, like so:
create function get_data ( type varchar2 ) return sys_refcursor as
ret_cur sys_refcursor;
begin
if type = 'EMP' then
open ret_cur for select * from emp;
elsif type = 'DEPT' then
open ret_cur for select * from dept;
end if;
return ret_cur;
end;However, if you're using
sys_refcursor to create a generic "open a query" function like the above you're probably doing something wrong!Code Snippets
create function get_data ( type varchar2 ) return sys_refcursor as
ret_cur sys_refcursor;
begin
if type = 'EMP' then
open ret_cur for select * from emp;
elsif type = 'DEPT' then
open ret_cur for select * from dept;
end if;
return ret_cur;
end;Context
StackExchange Database Administrators Q#34180, answer score: 11
Revisions (0)
No revisions yet.