Thursday, December 17, 2009

Is there a way to get a ref cursor from a PL/SQL table?


Is there a way to get a ref cursor from a PL/SQL table? I mean, I need to return a ref cursor from my Oracle function in order to see it as a recordset into VB. It is not a problem when the data I’m passing to the VB application comes from a query, even if the query has many tables involved. The problem appears when the data I need to pass is stored into a PL/SQL table in the form of a table of records.



Yes. The trick is to use a collection constructor and the TABLE() function. Let’s start by defining the types we need for our PL/SQL table:
create type FullName is object
( FirstName varchar2(30),
LastName varchar2(30)
);
create type NameList is table of FullName;
Next, we build our function:
create or replace function GetRefCursor
return sys_refcursor
is
myList NameList := NameList( FullName(’Eric’,'Clapton’),
FullName(’Robert’,'Plant’) );
Result sys_refcursor;
begin
open Result for select * from table(myList);
return Result;
end GetRefCursor;
By the way, this will work in Oracle 9i just fine, however, SYS_REFCURSOR is not defined in 8i. If you are using 8i, you will have to declare a type of REF CURSOR in a package specification and substitute that type in the place of SYS_REFCURSOR.

No comments: