Multiple SELECTS returned to a REF CURSOR

Hi there
I have a query regarding returning a REF Cursor from multiple selects and any input/hints would be greatly appreciated.
Basically, I have a select(from multiple tables) that returns a set of rows(query 1) and another (from multiple tables) that returns a set of data that needs to be appended to the results from query 1. Initially my thoughts were to join the queries using an inline view. This returns the correct number of rows but as there is only 1 field I can use to join the queries it is very inefficient and takes forever to execute.
So, I’ve there for had to rethink my design but have hit a brick wall – so to speak!
Is it possible to use one cursor for each query and return the results in 1 ref cursor?
I’m thinking I would need something like the following: -
Cursor 1 is
Select a.quote, b.name,c.price from table a,b,c
Cursor 2 (cursor 1.quote IN)
Is
Select * from table d,e,f
Where d.quote = cursor1.quote
What I need to output in the ref cursor is as follows: -
For each record returned from query 1, return the data from query 2.
Many thanks in advance
ps I'm using 9i

Do UNION or UNION ALL work on your version of Oracle? <g>

Similar Messages

  • Sorting the results returned by a Ref cursor

    Hi All,
    I have a scenario where i am asked to sort results returned by a ref cursor.
    I have to pass the column to be sorted as the Input parameter to a stored procedure. I tried using 'order by sorting_parameter' in the ref cursor's select query, but it is not sorting the results. It is not throwing any error even.
    Please help.
    Many Thanks...

    Hi
    i came across the below reply for a thread with the similar query as above.
    <<
    Justin Cave
    Posts: 10,696
    From: Michigan, USA
    Registered: 10/11/99
    Re: sort data in ref cursor
    Posted: Feb 3, 2005 10:30 AM in response to: [email protected] Reply
    No. You could sort the data in the SQL statement from which the REF CURSOR was created, but once you have a REF CURSOR, you cannot do anything but fetch from it.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC
    >>
    So, the results from a ref cursor cant be sorted?? There is no way out?
    Kindly advise.

  • Number of total rows returned by a ref cursor without using FETCH

    Hi. How can we get the total number of rows returned by a ref cursor without doing the FETCH? I mean, if you use %ROWCOUNT, it only returns the current row number being returned in every fetch. This is not what I want. My purpose is to determine if my query using ref cursor returns greater than zero total rows without using fetch. Thanks.

    As John pointed out in the thread you linked to, the only way to know how many rows a query will return is to actually fetch all the rows. Oracle doesn't know how many rows a query is going to return until it actually fetches the last row.
    Plus, assuming the default transaction isolation level, if you run the same query multiple times in succession, there is no guarantee that the results will be the same.
    If you just want to know whether a query will return a nonzero number of rows, why not just write the code to assume that it returns at least 1 row and handle the zero row result as an exception.
    Justin

  • How to create a procedure function with a return value of ref cursor?

    Can anybody provide a sample about how to create a procedure function with a return value of REF CURSOR?
    I heard if I can create a function to return a ref cursor, I can use VB to read its recordset.
    Thanks a lot.

    http://osi.oracle.com/~tkyte/ResultSets/index.html

  • Can the return from xsql:ref-cursor-function be saved & looped through XSQL?

    If <xsql:ref-cursor-function> returns one field for a number of rows, is there a way to save those values and loop through the data retrieved for other query process within XSQL? Any example?
    Thanks.
    null

    You have a couple of options.
    You can process the XML returned by <Xsql:ref-cursor-function> as the normal part of XSLT processing, or you can write a custom action handler that aggregates the action handler for <xsql:ref-cursor-function> and then uses DOM to operate on the return value.
    Search the Online XSQL Pages Documentation for the term "MyIncludeXSQLHandler" for some sample code that illustrates building a customer action handler that aggregates one of the built-in handlers.

  • Can a dynamic select stmt in a ref cursor be done?

    Hello all!
    I have a form in which a user can select a number of checkboxes that coorespond to fields in a table. After checking the desired boxes, the user can then click on a button and a variable (v_query) in a "when button pressed" trigger is populated with the text of a sql query. The trouble is, I want to incorporate the code contained in v_query into the REF cursor OPEN statement where it is expecting a sql query. The idea here is that the cursor would loop through the table fetching rows based on the select statement variable (v_query) and write them to a file using TEXT_IO(See below code). First, can this be done? Second, is there a better way to do accomplish this?
    DECLARE
    TYPE t_cur IS REF CURSOR ; -- define t_cur as a type
    c_cur t_cur ; -- define an actual variable of type t_cur
    r_emp emp%ROWTYPE ; -- PL/SQL record to hold row
    v_query VARCHAR2(2000) := 'SELECT * FROM emp' ; -- the query!
    BEGIN
    -- OPEN FILE
    out_file := Text_IO.Fopen('C:\BACHELOR\TEST.txt', 'w');
    OPEN c_cur FOR v_query ; -- v_query could contain any valid query
    LOOP
    FETCH c_cur INTO r_emp ; -- get first row from dataset
    EXIT WHEN %NOTFOUND
    --PRINT TO FILE 
              Text_IO.Put_line(out_file, r_emp);
              Text_IO.New_Line(out_file);
    END LOOP;
    CLOSE c_cur ; -- remember to close the cursor! ;)
    END;

    Hello all!
    I have a form in which a user can select a number of checkboxes that coorespond to fields in a table. After checking the desired boxes, the user can then click on a button and a variable (v_query) in a "when button pressed" trigger is populated with the text of a sql query. The trouble is, I want to incorporate the code contained in v_query into the REF cursor OPEN statement where it is expecting a sql query. The idea here is that the cursor would loop through the table fetching rows based on the select statement variable (v_query) and write them to a file using TEXT_IO(See below code). First, can this be done? Second, is there a better way to do accomplish this?
    DECLARE
    TYPE t_cur IS REF CURSOR ; -- define t_cur as a type
    c_cur t_cur ; -- define an actual variable of type t_cur
    r_emp emp%ROWTYPE ; -- PL/SQL record to hold row
    v_query VARCHAR2(2000) := 'SELECT * FROM emp' ; -- the query!
    BEGIN
    -- OPEN FILE
    out_file := Text_IO.Fopen('C:\BACHELOR\TEST.txt', 'w');
    OPEN c_cur FOR v_query ; -- v_query could contain any valid query
    LOOP
    FETCH c_cur INTO r_emp ; -- get first row from dataset
    EXIT WHEN %NOTFOUND
    --PRINT TO FILE 
              Text_IO.Put_line(out_file, r_emp);
              Text_IO.New_Line(out_file);
    END LOOP;
    CLOSE c_cur ; -- remember to close the cursor! ;)
    END;

  • Return XML from REF CURSOR

    It appears to be fairly straight-forward to get XML from a SQL query using the XML SQL Utility.
    Is it possible to use this utility (or another) to get XML from a cursor variable as well? I would like to generate overloaded get_xml functions in a PL/SQL package that will accept either SQL or a weak type REF CURSOR and return XML.

    Thanks for the help. Actually, I just bought your book and was getting ready to do some research. This should get me pointed in the right direction.
    Does the PL/SQL API lack this functionality? I wasn't sure whether to implement this in PL/SQL or Java, but the decision may be made for me...

  • [b]HELP-Accessing REF CURSOR (select *   from *) from OCI[/b]

    I have a stored procedure that returns a weak REF CURSOR as an out parameter. I want to access the rows that are returned, in an OCI application. I want a sample OCI program that does this. The PL/SQL code is as follows
    PACKAGE TEST_PACKAGE AS
    TYPE RCT IS REF CURSOR;
    END;
    PROCEDURE TEST_PROCEDURE (R OUT TEST_PACKAGE.RCT)
    AS
    BEGIN
    OPEN r FOR
    SELECT * FROM XXX;
    END;
    THANKS.

    Hello,
    I used in my application regular connections, I created
    CallableStatement with these connections, later I got one cursor with:
    mr = ((OracleCallableStatement)cstmt).getCursor(1)
    where mr is ResultSet and cstmt is CallableStatement.
    But, when I use the Commerce PoolConnection I get serialConnection
    and it creates serialCallableStatement and the command:
    mr = ((OracleCallableStatement)cstmt).getCursor(1)
    get the next exception:
    java.lang.ClassCastException:
    weblogic.jdbc20.rmi.SerialCallableStatement at......
    Are you working with Bea ConnectionPool
    or regular Connections?
    Thank you.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Matt Sivertson ([email protected]):
    I'm having a very strange problem with some JDBC code. Basically, there is a StoredProcedure in the DB that we call through JDBC. One of the out parameters is a REF CURSOR. My user does not have select access to the table, but the stored procedure does. When I try and get the ResultSet corresponding to that RefCursor using the OracleCallableStatement.getCursor() method, and exception gets thrown saying it cannot find the table. We checked on the database, and it is actually performing a new select statement as My user, rather than as the StoredProcedure. If we open up the permissions on the table, everything works fine, but this defeats the whole purpose of what the DBA wants.
    BTW, this same Stored Procedure works when fine when accesed through PL/SQL or SQL+. Only JDBC seems to have a problem with it. Any help is greatly appreciated.
    Matt Sivertson
    [email protected]<HR></BLOCKQUOTE>
    null

  • PLS-00428 Why SELECT must be adorned with REF CURSOR to work?

    hello
    *"PLS-00428: an INTO clause is expected in this SELECT statement"* - This problem has been resolved. I just want to understand WHY SELECT statements need to be paired with REF CURSOR.
              To reproduce this,
                   DECLARE
                        Id1 numeric(19,0);
                        Id2 numeric(19,0);
                        CreateTimestamp date;
                   BEGIN
                   -- ATTN: You'd either need to select into variable or open cursor!
                   select * from SystemUser left join Person on Person.Id = SystemUser.PersonId WHERE Person.PrimaryEmail in ('[email protected]','[email protected]');
                   END;
              Solution?
                   * In install script:
                        CREATE OR REPLACE PACKAGE types
                        AS
                             TYPE cursorType IS REF CURSOR;
                        END;
                   * Then in your query:
                        DECLARE
                             Id1 numeric(19,0);
                             Id2 numeric(19,0);
                             Result_cursor types.cursorType;
                        BEGIN
                        OPEN Result_cursor FOR select * from SystemUser left join Person on Person.Id = SystemUser.PersonId WHERE Person.PrimaryEmail in ('[email protected]','[email protected]');
                        END;
    I Googled for reasonable explaination - closest is: http://www.tek-tips.com/viewthread.cfm?qid=1338078&page=34
    That in oracle block or procedures are expected to do something and a simple SELECT is not!! (Very counter intuitive). What needs to be done is therefore to put the select output into a ref-cursor to fool oracle so that it thinks the procedure/block is actually doing something. Is this explanation right? Sounds more like an assertion than actually explaining...
    Any suggestion please? Thanks!

    Opening a cursor (ref cursor or otherwise) is not the same as executing a select statement.
    A select statement returns data, so if you are using it inside PL/SQL code it has to return that data into something i.e. a local variable or structure. You can't just select without a place for the data to go.
    Opening a cursor issues the query against the database and provides a pointer (the ref cursor), but at that point, no data has been retrieved. The pointer can then be used or passed to some other procedure or code etc. so that it may then fetch the data into a variable or structure as required.
    It's not counter-intuitive at all. It's very intuitive.

  • Ref cursor return type

    i am using a ref cursor as out parameter in a stored procedure.
    When I call the stored procedure and want to retrieve the rows returned by the ref cursor,
    is there a way to fetch the records using something like %ROWTYPE if I donot know the type of rows returned by the cursor.
    eg.
    procedure my_test_ref_cursor ( a OUT SYS_REFCURSOR) IS
    BEGIN
    OPEN a FOR SELECT EMP_ID, EMP_NAME FROM EMP;
    END;
    procedure call_my_test_ref_cursor is
    b sys_refcursor;
    begin
    my_test_ref_cursor(b);
    fetch b into XXXXXXX - if this program doesnot know the type of ref cursor 'b' is pointing to is there a way to use
    something like %ROWTYPE here ?
    end;

    While you can use the logic to return a weakly typed reference cursor, there should be a compelling why. A strongly typed reference cursor may be a better solution. You define a strongly typed reference cursor inside a package, and you anchor it to a ROWTYPE. Weakly typed reference cursors are typically useful when you are working with a subset of a table because you can't anchor to part of a table. However, you can define a view that uses the portion of the table and anchor a strongly typed reference cursor to the view.
    A strongly typed PL/SQL reference cursor is defined like this in a package specification:
    TYPE strongly_typed_cursor IS REF CURSOR RETURN some_table%ROWTYPE;
    So, if you rewrote it like this ...
    PROCEDURE my_test_ref_cursor (a OUT SOME_PACKAGE.STRONGLY_TYPED_CURSOR) IS
    BEGIN
    OPEN a FOR SELECT emp_id, emp_name FROM emp;
    END;
    Now, you can access it like this ...
    PROCEDURE call_my_test_ref_cursor IS
    another_var SOME_PACKAGE.STRONGLY_TYPED_CURSOR;
    target SOME_TABLE%ROWTYPE;
    BEGIN
    my_test_ref_cursor(another_var);
    LOOP
    FETCH another_var INTO target;
    EXIT WHEN another_var%NOTFOUND;
    dbms_output.put_line('See it '||target.emp_name||'.');
    END LOOP;
    END;
    The DBMS_SQL method you're looking for is Method 4. My recollection is that there isn't a good example in the docs but I could be wrong ... The OCI works no differently, nor does the JDBC interface. Hope this helps.

  • Ref cursor to object  and return to ref cursor

    how i will call object type from refcursor and return value to ref cursor .

    I need a help. please help me.
    takes oracle object types as input/output.
    PROCEDURE createserviceorder(
    P_serviceorder IN serviceorder,
    P_serviceid in out p_sm_type.serviceid,
    P_serviceorderid out p_sm_type.serviceorderid,
    Returnstatus out callstatus);
    The serviceorder, callstatus are oracle object types.
    The wrapper procedure for this API would be something like the example with pseudo code below
    PROCEDURE createserviceorderwrapper(
    P_serviceorder IN REFCURSOR,
    P_serviceid in out p_sm_type.serviceid,
    P_serviceorderid out p_sm_type.serviceorderid,
    Returnstatus out REFCURSOR)
    Map from ref cursor P_serviceorder to oracle object for serviceorder;
    Map from other data types to local variables;
    Call createserviceorder (pass the parameters here and get output….);
    Map output callstatus to its equivalent REF CURSOR variable;
    Return callstatus (and other out parameters if any )as REF CURSORS;
    }

  • Ref cursor and dynamic sql

    Hi..
    I'm using a ref cursor query to fetch data for a report and works just fine. However i need to use dynamic sql in the query because the columns used in the where condition and for some calculations may change dynamically according to user input from the form that launches the report..
    Ideally the query should look like this:
    select
    a,b,c
    from table
    where :x = something
    and :y = something
    and (abs(:x/:y........)
    The user should be able to switch between :x and :y
    Is there a way to embed dynamic sql in a ref cursor query in Reports 6i?
    Reports 6i
    Forms 6i
    Windows 2000 PRO

    Hello Nicola,
    You can parameterize your ref cursor by putting the query's select statement in a procedure/function (defined in your report, or in the database), and populating it based on arguments accepted by the procedure.
    For example, the following procedure accepts a strongly typed ref cursor and populates it with emp table data based on the value of the 'mydept' input parameter:
    Procedure emp_refcursor(emp_data IN OUT emp_rc, mydept number) as
    Begin
    -- Open emp_data for select all columns from emp where deptno = mydept;
    Open emp_data for select * from emp where deptno = mydept;
    End;
    This procedure/function can then be called from the ref cursor query program unit defined in your report's data model, to return the filled ref cursor to Reports.
    Thanks,
    The Oracle Reports Team.

  • Ref Cursors / throwing data into a Ref Cursor as data is fetched

    I was wondering if anyone has executed an SQL statement and as each row is being fetched back from an SQL, doing some data checks and processing to see if the row is valid to return or not, based on the values being fetched in an SQL.
    For example, I'm taking an SQL statement and trying to do some tuning. I have an Exists clause in the Where statement that has a nested sub-query with some parameters passed in. I am attempting to move that statement to a function call in a package (which is called in the SELECT statement). As I fetch each row back, I want to check some values that are Selected and if the values are met, then, I want to execute the function to see if the data exists. If it does exist, then, I want the fetched row returned in the Ref Cursor. If the criteria is met and the row doesn't exist in the function call, then, I don't want the fetched row to return.
    Right now, the data has to be thrown to REF Cursor because it's being outputted to the Java application as a Result Set.
    I've found many statements where you can take a SELECT statement and throw the Results in the Ref Cursor. But, I want to go a step further and before I throw each row in the Ref Cursor, I want to some processing to see if I put the Fetched Row in the Ref Cursor.
    If someone has a better idea to accomplish this, I'm all ears. Like I say, I'm doing this method only for the sake of doing some database tuning and I think this will speed things up. Having the EXISTS clause works and it runs fast from an End-user standpoint but, when it processes on the database with the nested subquery, it is slow.
    Here's an example of something that might be a problem (Notice the nested subquery). I moved the nested subquery to a function call written on the database package and make the call to the procedure/package in the SELECT statement. As I process each row, I want to check some values prior having the function call execute. If it meet some criteria, then the record is Ok to fetch and display in the Ref Cursor. If it does not meet the criteria and goes through the function and doesn't return data, then, I don't want the Fetched row from the main query to return the data.:
    SELECT EMPNO,
    FIRST_NAME,
    LAST_NAME
    FROM EMP E,
    DEPT D
    WHERE E.DEPTNO = D.DEPTNO
    AND EXISTS (SELECT 'X'
    FROM MANAGER M
    WHERE M.MANAGER_ID = E.MANAGER_ID
    AND MANAGER_TYPE IN (SELECT MANAGER_TYPE
    FROM MANAGER_LOOKUP ML WHERE ML.MANAGER_TYPE = M.MANAGER_TYPE))
    Any help or ideas of other things to try is appreciated. Keep in mind that I am returning this data to the Java application so, throwing the data to a Ref Cursor in the PL/SQL is the ideal method.
    Chris

    Ref cursors are not required nor desirable when writing java database application. Cursors are mentioned only once in the JDBC documentation reference guide, in the section "Memory Leaks and Running Out of Cursors".
    In a word cursors are just plain ridiculous, and in fact I never used them in my 15+ years of application development practice:
    http://vadimtropashko.wordpress.com/cursors/

  • Hyperion get ref cursor data

    Hi,
    Is there any way to execute stored procedure via hyperion using ODBC and get back ref cursor data.
    I tried to call a stored procedure that have a ref cursor out parameter but it gives me error.
    My stored procedure code is below.
    wrong number or types of arguments to in call to 'HYP_CURSOR'
    create or replace package hyp_ref_cusrsor is
    type t_cusror is ref cursor;
    end;
    create or replace procedure hyp_cursor(ret1 out hyp_ref_cusrsor.t_cusror) is
    begin
    open  ret1 for select * from hyp_tmp1 m;
    end;
    Hyperion version is 9.3.1
    Oracle version is 10.0.2
    Regards

    George wrote:
    Is there a limit to the volume of data a ref cursor can return via an Oracle Database Procedure call? No.
    {thread:id=886365}
    Re: OPEN cursor for large query
    A ref cursor is a pointer to a compiled SQL statement, it has no rows so there is no limit to the number of rows that you can use it to fetch, just like there is no limit to the number of rows a select can return.
    I am using a ref cursor to return data and testing using toad, it hangs the session. My Business Object report also hangs because of the large data volume 750,000 rows returned via a ref cursor. This is very confusing, it it hangs how do you know it returns 750,000 rows?

  • Dynamic REF Cursor with Dynamic Fetch - Urgent

    i have a pl/sql package with generates dynamic SQL statments. my problem is i want to open this SQL statment dynamically and fetch data in dynamic variable.
    declare
    type type_temp is REF CURSOR;
    cur_temp type_temp;
    mv_sql varchar2(4000);
    begin
    -- this will be dunamically generated and
    -- hence could have any no. of columns.
    mv_sql := select f1, f2, f3, f4 from table_temp;
    open cur_temp for mv_sql;
    fetch cur_temp into c1, c2, c3, c4;
    close cur_temp;
    end;
    problem is my sql statment will have N no. of columns how can i fetch this N no. of columns.

    Very hard problem, because ref cursors do not (directly) support description!
    Se mine (non-ideal) solution (it may be doable, but it isn't very practical
    or easily maintainable):
    1. "Generic" package
    CREATE OR REPLACE PACKAGE dyn_fetch IS
    TYPE ref_cur_t IS REF CURSOR;
    g_query VARCHAR2 (32000);
    g_count NUMBER;
    g_desc_tab DBMS_SQL.DESC_TAB;
    varchar2_type CONSTANT PLS_INTEGER := 1;
    number_type CONSTANT PLS_INTEGER := 2;
    date_type CONSTANT PLS_INTEGER := 12;
    rowid_type CONSTANT PLS_INTEGER := 11;
    char_type CONSTANT PLS_INTEGER := 96;
    long_type CONSTANT PLS_INTEGER := 8;
    raw_type CONSTANT PLS_INTEGER := 23;
    mlslabel_type CONSTANT PLS_INTEGER := 106;
    clob_type CONSTANT PLS_INTEGER := 112;
    blob_type CONSTANT PLS_INTEGER := 113;
    bfile_type CONSTANT PLS_INTEGER := 114;
    PROCEDURE describe_columns;
    FUNCTION record_def RETURN VARCHAR2;
    END;
    CREATE OR REPLACE PACKAGE BODY dyn_fetch IS
    PROCEDURE describe_columns IS
    l_cur INTEGER;
    BEGIN
    l_cur := DBMS_SQL.OPEN_CURSOR;
    DBMS_SQL.PARSE (l_cur, g_query, DBMS_SQL.NATIVE);
    DBMS_SQL.DESCRIBE_COLUMNS (l_cur, g_count, g_desc_tab);
    DBMS_SQL.CLOSE_CURSOR (l_cur);
    EXCEPTION
    WHEN OTHERS THEN
    IF DBMS_SQL.IS_OPEN (l_cur) THEN
    DBMS_SQL.CLOSE_CURSOR (l_cur);
    END IF;
    RAISE;
    END;
    FUNCTION record_def RETURN VARCHAR2 IS
    l_record_def VARCHAR2 (32000);
    l_type VARCHAR2 (100);
    l_col_type PLS_INTEGER;
    l_col_max_len PLS_INTEGER;
    l_col_precision PLS_INTEGER;
    l_col_scale PLS_INTEGER;
    BEGIN
    FOR i IN 1..g_count LOOP
    l_col_type := g_desc_tab(i).col_type;
    l_col_max_len := g_desc_tab(i).col_max_len;
    l_col_precision := g_desc_tab(i).col_precision;
    l_col_scale := g_desc_tab(i).col_scale;
    IF l_col_type = varchar2_type THEN
    l_type := 'VARCHAR2(' || l_col_max_len || ')';
    ELSIF l_col_type = number_type THEN
    l_type := 'NUMBER(' || l_col_precision || ',' || l_col_scale || ')';
    ELSIF l_col_type = date_type THEN
    l_type := 'DATE';
    ELSIF l_col_type = rowid_type THEN
    l_type := 'ROWID';
    ELSIF l_col_type = char_type THEN
    l_type := 'CHAR(' || l_col_max_len || ')';
    -- ELSIF l_col_type = ...
    -- long_type, raw_type ...
    END IF;
    l_record_def := l_record_def || ' col_' || i || ' ' || l_type || ',';
    END LOOP;
    l_record_def := RTRIM (l_record_def, ',');
    RETURN l_record_def;
    END;
    END;
    Note that procedure "record_def" creates columns names as col_1 (col_2 ...)
    because SELECT clause in your query can be without aliases, for example
    "SELECT deptno || dname FROM dept".
    2. Your package which returns query nad ref cursor
    CREATE OR REPLACE PACKAGE test IS
    PROCEDURE set_query (p_query VARCHAR2 := NULL);
    FUNCTION ref_cur RETURN dyn_fetch.ref_cur_t;
    END;
    CREATE OR REPLACE PACKAGE BODY test IS
    PROCEDURE set_query (p_query VARCHAR2 := NULL) IS
    l_query VARCHAR2 (32000) :=
    ' SELECT e.empno, e.ename,' ||
    ' e.deptno, d.dname' ||
    ' FROM emp e,' ||
    ' dept d' ||
    ' WHERE e.deptno = d.deptno';
    BEGIN
    IF p_query IS NULL THEN
    dyn_fetch.g_query := l_query;
    ELSE
    dyn_fetch.g_query := p_query;
    END IF;
    END;
    FUNCTION ref_cur RETURN dyn_fetch.ref_cur_t IS
    l_ref_cur dyn_fetch.ref_cur_t;
    BEGIN
    OPEN l_ref_cur FOR dyn_fetch.g_query;
    RETURN l_ref_cur;
    END;
    END;
    Why we need two separate procedures (functions) in your package ?
    a) Receiving program must use dynamic SQL, but in dynamic block we can access
    only PL/SQL code elements that have global scope (standalone functions and procedures,
    and elements defined in the specification of a package).
    Unfortunately, cursor variables cannot be defined in the specification of a package
    (cannot be global variables).
    b) Receiving program must get the column list before ref cursor.
    So, we have two options: call (in receiving program) the same function two times
    (once to get the column list and once to return a ref cursor)
    or use one procedure (or function) for returning query (to get the column list)
    and second function for returning a ref cursor.
    3. Your receiving program
    CREATE OR REPLACE PROCEDURE test_fetch_ref_cur (p_query VARCHAR2 := NULL) IS
    l_statement VARCHAR2 (32000);
    FUNCTION process_def RETURN VARCHAR2 IS
    l_process_def VARCHAR2 (32000);
    BEGIN
    l_process_def := 'DBMS_OUTPUT.PUT_LINE (';
    FOR i IN 1 .. dyn_fetch.g_count LOOP
    l_process_def := l_process_def || ' l_record.col_' || i || ' || ''>>'' || ';
    END LOOP;
    l_process_def := RTRIM (l_process_def, ' || ''>>'' || ') || ');';
    RETURN l_process_def;
    END;
    BEGIN
    test.set_query (p_query);
    dyn_fetch.describe_columns;
    l_statement :=
    ' DECLARE' ||
    ' TYPE record_t IS RECORD (' ||
    dyn_fetch.record_def || ');' ||
    ' l_record record_t;' ||
    ' l_ref_cur dyn_fetch.ref_cur_t;' ||
    ' BEGIN' ||
    ' l_ref_cur := test.ref_cur;' ||
    ' LOOP' ||
    ' FETCH l_ref_cur INTO l_record;' ||
    ' EXIT WHEN l_ref_cur%NOTFOUND;' ||
    process_def ||
    ' END LOOP;' ||
    ' CLOSE l_ref_cur;' ||
    ' END;';
    EXECUTE IMMEDIATE l_statement;
    END;
    You can test this with:
    SET SERVEROUTPUT ON;
    EXECUTE test_fetch_ref_cur;
    Note that we can try to use more generic solution:
    CREATE OR REPLACE PACKAGE dyn_fetch IS
    -- SAME AS BEFORE, PLUS:
    PROCEDURE fetch_ref_cur (
    p_function_ref_cur VARCHAR2,
    p_process_def VARCHAR2);
    END;
    CREATE OR REPLACE PACKAGE BODY dyn_fetch IS
    -- SAME AS BEFORE, PLUS:
    PROCEDURE fetch_ref_cur (
    p_function_ref_cur VARCHAR2,
    p_process_def VARCHAR2)
    IS
    l_statement VARCHAR2 (32000);
    BEGIN
    l_statement :=
    ' DECLARE' ||
    ' TYPE record_t IS RECORD (' ||
    record_def || ');' ||
    ' l_record record_t;' ||
    ' l_ref_cur dyn_fetch.ref_cur_t;' ||
    ' BEGIN' ||
    ' l_ref_cur := ' ||
    p_function_ref_cur || ';' ||
    ' LOOP' ||
    ' FETCH l_ref_cur INTO l_record;' ||
    ' EXIT WHEN l_ref_cur%NOTFOUND;' ||
    p_process_def ||
    ' END LOOP;' ||
    ' CLOSE l_ref_cur;' ||
    ' END;';
    EXECUTE IMMEDIATE l_statement;
    END;
    END;
    CREATE OR REPLACE PROCEDURE test_fetch_ref_cur (p_query VARCHAR2 := NULL) IS
    FUNCTION process_def RETURN VARCHAR2 IS
    -- SAME AS BEFORE
    END;
    BEGIN
    test.set_query (p_query);
    dyn_fetch.describe_columns;
    dyn_fetch.fetch_ref_cur (
    p_function_ref_cur => 'test.ref_cur',
    p_process_def => process_def);
    END;
    Regards,
    Zlatko Sirotic

Maybe you are looking for