Cursor with in a REF CURSOR

Hi All,
I am having a REF cursor returned by a function which contains a CURSOR with in its select statement. Can any one please let me know how to fetch these values into variable for further processing. A sample query for my REF CURSOR is
Select dept_id,
cursor(
select emp_id, emp_name
from emp e
where e.dept_id = d.dept_id)
from dept d

SQL> l
  1  create function fun
  2     return sys_refcursor
  3  is
  4     retval sys_refcursor;
  5  begin
  6     open retval for select object_id
  7                          , cursor (select dummy
  8                                      from dual
  9                                   )
10                       from all_objects
11                      where rownum <= 10;
12     return retval;
13* end fun;
SQL>
SQL>
SQL>
SQL> var rc refcursor
SQL> exec :rc := fun
PL/SQL procedure successfully completed.
SQL> print :rc
OBJECT_ID CURSOR(SELECTDUMMYFR
        20 CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
D
        51 CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
D
X
        26 CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
D
X
10 rows selected.
SQL>

Similar Messages

  • Is BC4J a viabl option for database with stored procedure (ref cursor) API?

    I'm about to begin a Web application development project. As foundation, we have a (Oracle) database of certain complexity that have a data access API developed with PL/SQL packages.
    This API is designed to get data through stored procedures/functions that return REF CURSOR.
    Personally I have been investigating about Oracle ADF/JSF, and a number of others J2EE technologies, and at this moment I am doubting if ADF BC are a viable option to my development team.
    I think this because I have noticed that one of the great drawback in ADF BC is the lack of simplicity to get data through stored procedures/functions that returns REF CURSORS.
    I have been looking for documentation and the only thing that I have found are two examples:
    1.- One that really do not work (fails in get data from ref cursor): ADF BC StoredProcedure Sample application.
    2.- And other published by Steve Muench in
    http://radio.weblogs.com/0118231/stories/2003/03/03/gettingAViewObjectsResultRowsFromARefCursor.html. This sample works fine.
    But, the problem with the approach of this last article is the amount (and complexity) of the code necessary to make so basic and recurrent operation as is "obtain data through a stored procedure (ref cursor)".
    Below it is the code that I have constructed to call a function that returns a ref cursor (based on steve's article).
    If this is the only way to make this (historically so basic and simple) task, then it is obvious that BC is not a viable technology to my (or I am in a mistake?), since we have about 50 stored procedures/functions to access the underlying data; that stored procedures/functions are key to development of the new application (and, still more, currently are used to anothers apps ).
    By all this, I would like consult to Oracle's people:
    1.- I really must reject BC as technology to implement this project ?
    2.- It is possible to access stored procedures in a simpler way using BC?
    3.- If the answer to 2 is NOT: in near future, the BC team has plans to give more support to the simple access to stored procedures?
    4.- If the answer to 3 is NOT: what another technology you recommend to construct my data access/business tier and still be able to using the others characteristics of ADF?
    Thank you very much for your guidelines.
    Regards, RL.
    ** And the code!!!
    ** ###   I am forced to do this for each call to a procedure???? ###
    package myrefcursor.model;
    import java.math.BigDecimal;
    import java.sql.CallableStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Types;
    import oracle.jbo.JboException;
    import oracle.jbo.domain.NullValue;
    import oracle.jbo.domain.Number;
    import oracle.jbo.server.DBTransaction;
    import oracle.jbo.server.ViewObjectImpl;
    import oracle.jbo.server.ViewRowImpl;
    import oracle.jbo.server.ViewRowSetImpl;
    import oracle.jdbc.driver.OracleCallableStatement;
    import oracle.jdbc.driver.OracleTypes;
    public class TraePolizasViewImpl extends ViewObjectImpl {
        private static final String SQL = "begin ? := PKG_PRUEBA.trae_polizas(?);end;";
        private static final String COUNTSQL = "begin ? := PKG_PRUEBA.count_trae_polizas(?);end;";
        public TraePolizasViewImpl() {
        protected void executeQueryForCollection(Object qc,Object[] params,int numUserParams) {
            BigDecimal rut_contratante = null;
            Object[] theUserParam = null;
            System.out.println(params);
            System.out.println(params[0]);
            if (params != null)
                theUserParam = (Object[]) params[0];
            //if (theUserParam != null && theUserParam.length > 0 )
            if (! (theUserParam[1]   instanceof NullValue) )
                rut_contratante = (BigDecimal)theUserParam[1];
            storeNewResultSet(qc ,retrieveRefCursor(qc, rut_contratante));
            super.executeQueryForCollection(qc, params, numUserParams);
        protected void create() {
          getViewDef().setQuery(null);
          getViewDef().setSelectClause(null);
          setQuery(null);
        protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {
          rs = getResultSet(qc);
          ViewRowImpl r = createNewRowForCollection(qc);
          try {
            populateAttributeForRow(r,0, nullOrNewNumber(rs.getBigDecimal(1)));
            populateAttributeForRow(r,1, rs.getString(2));
          catch (SQLException s) {
           throw new JboException(s);
          return r;
        protected boolean hasNextForCollection(Object qc) {
          ResultSet rs = getResultSet(qc);
          boolean nextOne = false;
          try {
            nextOne = rs.next();
            if (!nextOne) {
              setFetchCompleteForCollection(qc, true);
              rs.close();
          catch (SQLException s) {
           throw new JboException(s);
          return nextOne;
        protected void releaseUserDataForCollection(Object qc, Object rs) {
           ResultSet userDataRS = getResultSet(qc);
           if (userDataRS != null) {
            try {    userDataRS.close();    }
            catch (SQLException s) { ; }  
          super.releaseUserDataForCollection(qc, rs);
        public long getQueryHitCount(ViewRowSetImpl viewRowSet) {
          return viewRowSet.getRowCount();
        private ResultSet retrieveRefCursor(Object qc, BigDecimal rut_contratante) {
          CallableStatement st = null;
          try {
            st = getDBTransaction().createCallableStatement(SQL, DBTransaction.DEFAULT);
            st.registerOutParameter(1,OracleTypes.CURSOR);
            if (rut_contratante == null)
                st.setNull(2, Types.NUMERIC);
            else
                st.setBigDecimal(2, rut_contratante);
            st.execute();
            ResultSet rs = ((OracleCallableStatement)st).getCursor(1);
            rs.setFetchSize(getFetchSize());
            return rs ;
          catch (SQLException s) {
            throw new JboException(s);
          finally {try {st.close();} catch (SQLException s) {;}}
        private void storeNewResultSet(Object qc, ResultSet rs) {
          ResultSet existingRs = getResultSet(qc);
          if (existingRs != null) {
            try {existingRs.close();} catch (SQLException s) {;}  
          setUserDataForCollection(qc,rs);
          hasNextForCollection(qc); // Prime the pump with the first row.
        private ResultSet getResultSet(Object qc) {
            return (ResultSet)getUserDataForCollection(qc);
        private static Number nullOrNewNumber(BigDecimal b) {
             try {
               return b != null ? new Number(b) : null;
             catch (SQLException s) { ; }
             return null;
        public BigDecimal getprutcontratante() {
            return (BigDecimal)getNamedWhereClauseParam("prutcontratante");
        public void setprutcontratante(BigDecimal value) {
            setNamedWhereClauseParam("prutcontratante", value);
    }

    no?

  • Toplink support for stored procedure with 2 OUT  REF CURSOR ?

    Can Toplink StoredProcedureCall be used with Oracle PLSql procedure with 2 OUT parameters. Parameter type is Ref Cursor (Oracle PLSQL resulset)
    Regards

    In a TopLink StoredProcedureCall using an OUT CURSOR the cursor is assumed to map to the result set for the TopLink query.
    For example if you had a stored procedure READ_ALL_EMP that returned a out cursor of EMP rows, you could use that procedure in a TopLink mapped Employee class mapped to the EMP table and use the stored procedure in a ReadAllQuery for the Employee class.
    If the procedure does not return data that maps to objects, you can use a DataReadQuery to access the data. The out cursor would be returned as a Vector of DatabaseRows that contain the data from the cursor rows.
    If the procedures data is complex and does not map to objects, it may be better to access the procedure directly through JDBC.

  • Problem with accepting the Ref Cursor in c# program

    I am passing an argument as OUT Ref Cursor in a stored procedure. and calling the procedure from my c# program.
    I can connect the database successfully but am getting the error on calling the procedure.
    I am using the ODBC connection
    My procedure's signatures are like:
    CREATE OR REPLACE PACKAGE BODY packageName
    IS
    PROCEDURE GetOutput(returnCursor OUT Sys_RefCursor)
    AS
    BEGIN
    OPEN returnCursor FOR
    <<my select statement>>
    END GetOutput;
    END packageName;
    My function call is like:
    CString Extract::ExtractScript() const
         CString script;
         script.Format("{Call %s.%s()}", packageName,GetOutput);
         return script;
    I can compile the procedure successfully on Toad but while calling the procedure from the C# program it gives following error
    Connection Successful
    Problem executing SQL {Call packageName.GetOutput()}...
    ORA-06550: line 1, column 7:
    PLS-00306: wrong number or types of arguments in call to 'GetOutput'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    Message was edited by:
    user653288

    Hi Aga,
    Thanks for your response.
    I figured out the problem.
    I was using the ODBC connection which wasnt updated for Oracle 10g.
    I have updated that. Now its working fine.
    Thanks again
    Regards

  • Ref cursors and dynamic sql..

    I want to be able to use a fuction that will dynamically create a SQL statement and then open a cursor based on that SQL statement and return a ref to that cursor. To achieve that, I am trying to build the sql statement in a varchar2 variable and using that variable to open the ref cursor as in,
    open l_stmt for refcurType;
    where refcurType is a strong ref cursor. I am unable to do so because I get an error indication that I can not use strong ref cursor type. But, if I can not use a strong ref cursor, I will not be able to use it to build the report based on the ref cursor because Reports 9i requires strong ref cursors to be used. Does that mean I can not use dynamic sql with Reports 9i ref cursors? Else, how I can do that? Any documentation available?

    Philipp,
    Thank you for your reply. My requirement is that, sometimes I need to construct a whole query based on some input, and sometimes not. But the output record set would be same and the layout would be more or less same. I thought ref cursor would be ideal. Ofcourse, I could do this without dynamic SQL by writing the SQL multiple times if needed. But, I think dynamic SQL is a proper candidate for this case. Your suggestion to use lexical variable is indeed a good alternative. In effect, if needed, I could generate an entire SQL statement and place in some place holder (like &stmt) and use it as a static SQL query in my data model. In that case, why would one ever need ref cursor in reports? Is one more efficient over the other? My guess is, in the lexical variable case, part of the processing (like parsing) is done on the app server while in a function based ref cursor, the entire process takes place in the DB server and there is probably a better chance for re-use(?)
    Thanks,
    Murali.

  • Ref Cursor over Implicit and explicit cursors

    Hi,
    In my company when writing PL/SQL procedure, everyone uses "Ref Cursor",
    But the article below, says Implicit is best , then Explicit and finally Ref Cursor..
    [http://www.oracle-base.com/forums/viewtopic.php?f=2&t=10720]
    I am bit confused by this, can any one help me to understand this?
    Thanks

    SeshuGiri wrote:
    In my company when writing PL/SQL procedure, everyone uses "Ref Cursor",
    But the article below, says Implicit is best , then Explicit and finally Ref Cursor..
    [http://www.oracle-base.com/forums/viewtopic.php?f=2&t=10720]
    I am bit confused by this, can any one help me to understand this?There is performance and there is performance...
    To explain. There is only a single type of cursor in Oracle - that is the cursor that is parsed and compiled by the SQL engine and stored in the database's shared pool. The "+client+" is then given a handle (called a SQL Statement Handle in many APIs) that it can use to reference that cursor in the SQL engine.
    The performance of this cursor is not determined by the client. It is determined by the execution plan and how much executing that cursor cost ito server resources.
    The client can be Java, Visual Basic, .Net - or a PL/SQL program. This client language (a client of SQL), has its own structures in dealing with that cursor handle received from the SQL engine.
    It can hide it from the developer all together - so that he/she does not even see that there is a statement handle. This is what implicit cursors are in PL/SQL.
    It can allow the developer to manually define the cursor structure - this is what explicit cursors, ref cursors, and DBMS_SQL cursors are in PL/SQL.
    Each of these client cursor structures provides the programmer with a different set of features to deal with SQL cursor. Explicit cursor constructs in PL/SQL do not allow for the use of dynamic SQL. Ref cursors and DBMS_SQL cursors do. Ref cursors do not allow the programmer to determine, at run-time, the structure of the SQL projection of the cursor. DBMS_SQL cursors do.
    Only ref cursors can be created in PL/SQL and then be handed over to another client (e.g. Java/VB) for processing. Etc.
    So each of the client structures/interfaces provides you with a different feature set for SQL cursors.
    Choosing implicit cursors for example does not make the SQL cursor go faster. The SQL engine does not know and does not care, what client construct you are using to deal with the SQL cursor handle it gave you. It does not matter. It does not impact its SQL cursor performance.
    But on the client side, it can matter - as your code in dealing with that SQL cursor determines how fast your interaction with that SQL cursor is. How many context switches you make. How effectively you use and re-use the SQL (e.g. hard parsing vs soft parsing vs re-using the same cursor handle). Etc.
    Is there any single client cursor construct that is better? No.
    That is an ignorant view. The client language provides a toolbox, where each tool has a specific application. The knowledgeable developer will use the right tool for the job. The idiot developer will select one tool and use it as The Hammer to "solve" all the problems.

  • Using Ref Cursors as region source

    Is it possible to use a function that returns a ref cursor as a region's source? I asked this question at the end of another thread and got no response so I made this new thread.
    I created an application called 'ref cursor' on apex.oracle.com at
    http://apex.oracle.com/pls/otn/f?p=4550
    Workspace : wc_jason
    username: dev
    password: password
    There is a table named TBL and a function returning a ref cursor name FNC. On the home page there are three regions, one using a sql statement, one using a pl/sql function returning a sql statement, and one that attempts to use a ref cursor. The ref cursor region's condition is set to NEVER because I couldn't get it to work and I wanted to show the page with the two working regions.
    Can I even use a ref cursor in this manor?
    Thanks for the help.

    Heres a quick example I did for you:
    create or replace package pkg_refcursordemo
    as
    type rc_generic is ref cursor;
    rec_emp emp%rowtype;
    type tab_emp is table of emp%rowtype;
    procedure proc_get_emp (
    pi_ename in emp.ename%type
    ,pio_emp_rc in out rc_generic
    function func_get_emp (
    pi_ename in emp.ename%type
    return tab_emp pipelined;
    end pkg_refcursordemo;
    create or replace package body pkg_refcursordemo
    as
    -- Procedure with in out ref cursor parameter
    procedure proc_get_emp (
    pi_ename in emp.ename%type
    ,pio_emp_rc in out rc_generic
    is
    begin
    open pio_emp_rc for
    select empno
    , ename
    , job
    , mgr
    , hiredate
    , sal
    , comm
    , deptno
    from emp
    where ename like pi_ename||'%';
    end proc_get_emp;
    -- Wrapper pipelined function
    function func_get_emp (
    pi_ename in emp.ename%type
    return tab_emp pipelined
    is
    l_rc_generic rc_generic;
    l_rec_emp emp%rowtype;
    begin
    proc_get_emp (
    pi_ename => pi_ename
    ,pio_emp_rc => l_rc_generic
    loop
    fetch l_rc_generic into l_rec_emp;
    exit when l_rc_generic%notfound;
    pipe row ( l_rec_emp );
    end loop;
    close l_rc_generic;
    return;
    end func_get_emp;
    end pkg_refcursordemo;
    create or replace view vw_emp
    as
    select empno
    , ename
    , job
    , mgr
    , hiredate
    , sal
    , comm
    , deptno
    from table ( pkg_refcursordemo.func_get_emp( null ) )
    SQL> select * from vw_emp;
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7369 SMITH CLERK 7902 17-DEC-80 800 20
    7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
    7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
    7566 JONES MANAGER 7839 02-APR-81 2975 20
    7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
    7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
    7782 CLARK MANAGER 7839 09-JUN-81 2450 10
    7788 SCOTT ANALYST 7566 19-APR-87 3000 20
    7839 KING PRESIDENT 17-NOV-81 5000 10
    7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
    7876 ADAMS CLERK 7788 23-MAY-87 1100 20
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7900 JAMES CLERK 7698 03-DEC-81 950 30
    7902 FORD ANALYST 7566 03-DEC-81 3000 20
    7934 MILLER CLERK 7782 23-JAN-82 1300 10
    14 rows selected.
    SQL>
    Whats cool is you can declare the view with an APEX variable in it e.g.
    create or replace view vw_emp
    as
    select empno
    , ename
    , job
    , mgr
    , hiredate
    , sal
    , comm
    , deptno
    from table ( pkg_refcursordemo.func_get_emp( v('P1_ENAME_PARAM' ) )
    /

  • Ref Cursor Output

    Hi,
    the I have the following procedure with an ref cursor as an output.
    CONCERN_ID_PK -- CONCERN_ID_FK -- ECN_ID_PK -- ECN_NO
    315 -- 315 -- 87 -- 4711
    i must store the values in variable like
    p_concern_id_pk
    p_concern_id_fk
    p_ecn_id_pk
    p_ecn_no
    because i want to call with the parameter an update procedure or/and an delete procedure.
    The select into statement doesn't work with an ref cursor I read.
    so what can be the solution for the problem ?
    I also have a types packes with the definief ref cursor
    type all_ecns is recursor;
    Must I use an self defined Object type or object table ????
    the procedures follows
    p_concern_id_pk in concern.concern_id_pk%TYPE,
    p_ecn_id_pk in ecn.ecn_id_pk%TYPE,
    p_ecncursor out types.all_ecns
    AS
    BEGIN
    OPEN p_ecncursor for select concern_id_pk, concern_id_fk, ecn_id_pk, ecn_no
    from ecn e,
    concern c
    where e.concern_id_fk = p_concern_id_pk
    and c.concern_id_pk = e.concern_id_fk
    and c.active = 1
    and ecn_id_pk = p_ecn_id_pk
    and c.active = 1;
    END;
    Thanks Marcel

    Is it something like this you're looking for?
    PACKAGE TYPES IS
    type tr is record (col1 tab1.col1%type, col2 tab1.col2%type);
    type tc is ref cursor returning tr;
    END;
    PROCEDURE get_data(p_cursor out types.tc) IS
    BEGIN
    open p_cursor for select col1,col2 from tab1;
    END;
    PROCEDURE process_data(p_cursor in types.tc)
    v_tr types.tr;
    BEGIN
    LOOP
    fetch p_cursor into v_tr;
    exit when p_cursor%notfound;
    dbms_output.put_line(v_tr.col1||' '||v_tr.col2);
    END LOOP;
    close p_cursor;
    END;

  • Ref cursor help in Reports/pl sql

    Hello , i am new to this , please help!
    From oracle forms, we have a table and one of the columns from that table returns rows and the result are like ( select name, messaging_id, listing_id from dynamic_message group_query) ..I am trying to join this table with other tables based on a group type, based on if it returns 'D' or 'S' to other groups in report.
    I am getting the following error when I uncomment the open cursor statemnt
    PLS-00455: cursor 'TEMP_GRP_REC_REFCUR' cannot be used in dynamic
    SQL OPEN statement
    This is what i have so faar:
    create or replace PACKAGE grp IS
    TYPE grp_rec IS RECORD
    (listing_id varchar2(16 ),
    messaging_id varchar2(16 ),
    name varchar2(256 ) ,
    group_number Number);
    TYPE grp_rec_refcur is REF CURSOR RETURN grp_rec;
    function grprefc(P_group_number NUMBER, P_group_type CHAR) return grp_rec_refcur;
    END;
    CREATE OR REPLACE PACKAGE BODY grp IS
    function grprefc(p_group_number Number )
    return grp_rec_refcur
    IS
    temp_grp_rec_refcur grp.grp_rec_refcur;
    v_stmt_str VARCHAR2(2000) := NULL;
    v_cov_name listing.name%TYPE := NULL;
    v_cov_mid listing.messaging_id%TYPE := NULL;
    v_cov_lid listing.listing_id%TYPE := NULL;
    v_grpnum message_group.group_number%TYPE := NULL;
    BEGIN
              v_stmt_str:='SELECT dmgq.resolved_query
              INTO v_stmt_str
              FROM dynamic_message_group_query dmgq
              WHERE dmgq.group_number = p_group_number';
    OPEN temp_grp_rec_refcur FOR v_stmt_str;
         LOOP
         FETCH temp_grp_rec_refcur INTO v_cov_lid , v_cov_mid ,v_cov_name, v_grpnum ;
         EXIT WHEN temp_grp_rec_refcur %NOTFOUND;
         END Loop;
         RETURN temp_grp_rec_refcur;
    END;
    END;
    show errors;
    if there are any examples done by someone in reoprts or if you can help me solve the above, i would higghly appreciate it .
    Thanks and Good Day!

    Maybe something like my second example "Dynamic Table in the Second Query with Oracle Reports"
    - ref cursor or "simple" query Q1, which has a column "group_type", linked to a ref cursor query Q2.
    Ref cursor query Q2 - pseudo code for function:
    CREATE OR REPLACE PACKAGE BODY grp IS
    FUNCTION A_join_B_or_A_join_C_join_D
      (p_group_type CHAR(1), p_group_number NUMBER)
      RETURN dynamic_refcur
    IS
      l_refcur dynamic_refcur;
      l_stmt_str VARCHAR2(2000) := NULL;
    BEGIN
      IF p_group_type = 'S' THEN
        -- join A and B
        OPEN l_refcur FOR
          SELECT ...
            FROM A, B
           WHERE A.x = B.y;
      ELSE -- p_group_type = 'D'
        SELECT resolved_query
          INTO l_stmt_str
          FROM dynamic_message_group_query
         WHERE group_number = p_group_number;
        -- join A, C and D (= dynamically created SELECT)
        OPEN l_refcur FOR
          'SELECT ...
             FROM A, C, (' || l_stmt_str || ') D
            WHERE A.x = C.y
              AND A.z = D.t';
      END IF;
      RETURN l_refcur;
    END;
    END; Regards,
    Zlatko

  • Ref Cursor closed returning to Form

    Hi,
    I came across this old thread which seems to be an exact match for my problem.
    sys ref cursor is closed
    And whereas the solutions do work as stated there is an issue with it that i wonder if anyone here has since got around.
    Take those examples and make the sql dynamic. on return to the form the ref cursor is instantaneouly closed for you making the thing unusable.
    i.e.
    OPEN cur FOR SELECT 'x' from dual
    works just fine but
    OPEN cur FOR 'SELECT ''X'' from dual'
    resutls in an closed cursor the moment the ref cursor parameter returns to the form. I need the dynamic form because my cursor is truly built dynamically.
    Any ideas anyone?

    Hi,
    try this :
    1. declare in the package specification
    TYPE rec_view IS RECORD(
      COL1        VARCHAR2(250),
      COL2        VARCHAR2(250),
      COL3        VARCHAR2(250),
      COL4        VARCHAR2(250),
      COL5        VARCHAR2(250)
      TYPE t_ref_curs IS REF CURSOR RETURN rec_view;
      TYPE t_rec_c IS REF CURSOR;
    2. define the dynamic sql - procedure
    PROCEDURE   prc_getdata (p_refcur IN OUT t_ref_curs, p_result OUT VARCHAR2,
                             p_filter IN varchar2 DEFAULT NULL, p_orderby In VARCHAR2 DEFAULT NULL)  IS
      BEGIN
            -- dyn cursor ! --
            EXECUTE IMMEDIATE
                    'BEGIN
                          OPEN :a FOR ' ||
                              ' select empno, ename, job, mgr, hiredate, sal  from emp'||' '||
                                p_filter  ||' '||
                                p_orderby ||'; '||
                     'END;'
               USING p_refcur;
       END prc_getdata;
    3. define in the Form a PL/SQL based block on this procedure.
    Hope it helps.
    Best regards
    Friedhold

  • How to get values from a ref cursor in a procedure

    I have a procedure that returns a cursor type of values, but I cannot get the values.
    I got error when on how to define the output cursor. Could someone please look at the code and tell me how to correct it?
    Thanks in advance.
    ******************************8
    --This is the package
    CREATE OR REPLACE PACKAGE Test_SECURITY2 as
    type T_RoleTest is ref cursor;
    Procedure P_GetUserRole(userID in number, p_cur out T_RoleTest);
    end;
    CREATE OR REPLACE PACKAGE BODY Test_SECURITY2 as
    Procedure P_GetUserRole(userID in number, p_cur out T_RoleTest) as
    begin
         open p_cur for
         select PREO_Role.ROLE_ID,PREO_Role.ROLE_NAME
         from preorder.PREO_Role, preorder.PREO_User_Role
         where PREO_Role.Role_id = PREO_User_Role.Role_id
         and PREO_User_Role.user_id = userid;
    end;
    end;
    --This is the testing code. I got error here
    SQL> set serveroutput on;
    SQL> execute dbms_output.enable;
    PL/SQL procedure successfully completed.
    SQL> declare
    2 type T_RoleTest is ref cursor;
    3 V_UserRole is ref cursor; --how to define the output cursor
    4 v_userId number := 42;
    5 V_Role_Id number;
    6 v_Role_name varchar2(20);
    7 begin
    8 Test_SECURITY2.P_GetUserRole(v_userId, V_UserRole);
    9
    10 open V_UserRole;
    11 loop
    12 fetch V_UserRole into V_Role_Id, v_Role_name;
    13
    14 EXIT WHEN V_UserRole%NOTFOUND;
    15 dbms_output.put_line('RoleID'||v_Role_ID);
    16 dbms_output.put_line('Rolename'||v_Role_name);
    17
    18 end loop;
    19
    20 end;
    21 /
    V_UserRole is ref cursor;
    ERROR at line 3:
    ORA-06550: line 3, column 13:
    PLS-00103: Encountered the symbol "IS" when expecting one of the following:
    constant exception <an identifier>

    declare
      type T_RoleTest is ref cursor;
      v_UserRole T_RoleTest;or just:
    declare
      v_UserRole  Test_Security2.T_RoleTest;And, if you are on 9i or later, you can just use the built-in sys_refcursor type.

  • How to accumlate resultsets in ref cursor

    Hello
    I have 3 cursor which query on different tables and return the same columns. I need to accumulate the result set of 3 cursors into a single ref cursor. Is this possible. If so how.
    regards,
    Ravi Narala

    It's possible, but it's not recommended. Do you have any control of the situation (can you just write 1 query)?
    If you have absolutely no option, you can user record types (you will need a SQL type created), BULK COLLECT the contents of cursor1, cursor2 and cursor3 into that, and then return a REF CURSOR that is
    SELECT * FROM TABLE(SQL_TYPE);
    Here's an example:
    create type my_number_type as table of number;
    DECLARE
       c1             sys_refcursor;
       c2             sys_refcursor;
       c3             sys_refcursor;
       final_cursor   sys_refcursor;  
       array_1        my_number_type;
       array_2        my_number_type;
       array_3        my_number_type;
       final_array    my_number_type;     
    BEGIN
       open c1 for select 1 from dual;
       fetch c1 bulk collect into array_1;
       close c1;
       open c2 for select 8 from dual;
       fetch c2 bulk collect into array_2;
       close c2;
       open c3 for select 6 from dual;
       fetch c3 bulk collect into array_3;
       close c3;
       select *
       bulk collect into final_array
       from
          select * from table(cast(array_1 as my_number_type))
          UNION ALL
          select * from table(cast(array_2 as my_number_type))
          UNION ALL
          select * from table(cast(array_3 as my_number_type))
       open final_cursor for select * from table(cast(final_array as my_number_type));
    END;
    [pre]
    Message was edited by:
            Tubby                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Using plsql table and ref cursor in oracle forms 10g

    Hi all,
    Can anyone give me an example of a scenario where we need to create a form manually based on a database stored procedures.
    And in that procedure i have created a pl/sql table and a ref cursor in data base level.
    CREATE OR REPLACE PACKAGE SCOTT.BONUS_PKG IS TYPE bonus_rec
    IS RECORD(
    empno     bonus_EMP.empno%TYPE,
    ename     bonus_EMP.ename%TYPE,
    job     bonus_EMP.job%TYPE,
    sal     bonus_EMP.sal%TYPE,
    comm     bonus_EMP.comm%TYPE);
    TYPE b_cursor IS REF CURSOR RETURN bonus_rec;
    TYPE bontab IS TABLE OF bonus_rec INDEX BY BINARY_INTEGER;
    PROCEDURE bonus_refcur(bonus_data IN OUT b_cursor);
    PROCEDURE bonus_query(bonus_data IN OUT bontab);
    END bonus_pkg;
    CREATE OR REPLACE PACKAGE BODY SCOTT.BONUS_PKG IS
    PROCEDURE bonus_query(bonus_data IN OUT bontab) IS
    ii NUMBER;
    CURSOR bonselect IS
    SELECT empno, ename, job, sal, comm FROM bonus_EMP ORDER BY empno;
    BEGIN
    OPEN bonselect;
    ii := 1;
    LOOP
    FETCH bonselect INTO
    bonus_data( ii ).empno,
    bonus_data( ii ).ename,
    bonus_data( ii ).job,
    bonus_data( ii ).sal,
    bonus_data( ii ).comm;
    EXIT WHEN bonselect%NOTFOUND;
    ii := ii + 1;
    END LOOP;
    END bonus_query;
    PROCEDURE bonus_refcur(bonus_data IN OUT b_cursor) IS
    BEGIN
    OPEN bonus_data FOR SELECT empno, ename, job, sal, comm FROM bonus_EMP ORDER BY empno;
    END bonus_refcur;
    END bonus_pkg;
    i want to populate the data in forms manually not using forms data block wizard and programmatically.
    please reply...

    Can anyone give me an example of a scenario where we need to create a form manually based on a database stored procedures.Typically, you would use a procedure based block when you have a collection of data from multiple tables presented in a Form and your user needs to be able to update the information displayed.
    From your code example, it looks like you are using Oracle Support document "Basing a Block on a Stored Procedure - Sample Code [ID 66887.1]". If this is the case, keep following the document - it walks you through all of the steps. There is no need to Manually configure things that the Data Block Wizard will perform for you!
    i want to populate the data in forms manually not using forms data block wizard and programmatically. Why? Let the Data Block Wizard take care of configuring your block based on a procedure for you. There is no need to manually loop through the data! I've actually done what you are attempting and it was more work than was needed. Let Forms do the work for you. :)
    If you absolutely must do things manually, I recommend you use the PROCEDURE bonus_query(bonus_data IN OUT bontab) instead of the bonus_refcur(bonus_data IN OUT b_cursor) . Then, in your code create a variable of type BONTAB and then call the bonus_query procedure. Then it is a simple case of looping through the table of records returned by the bonus_query procedure. For example:
    DECLARE
       t_bonus    bonus_pkb.bontab;
    BEGIN
       bonus_pkg.bonus_query(t_bonus);
       FOR i in 1 .. t_bonus.count LOOP
          :YOUR_BLOCK.EMPLOYEE_NUMBER := t_bonus(i).empno;
          :YOUR_BLOCK.EMPLOYEE_NAME := t_bonus(i).ename;
          :YOUR_BLOCK.EMPLOYEE_JOB := t_bonus(i).job;
          :YOUR_BLOCK.EMPLOYEE_SALARY := t_bonus(i).sal;
          :YOUR_BLOCK.EMPLOYEE_COMMISSION := t_bonus(i).comm;
       END LOOP;
    END;This code sample demonstrates the basics, but as it is sample code - you will have to adapt it to your situation.
    Also, I strongly recommend you look at the article InoL listed. This is a very comprehensive discussion on REF CURSORs. If you are set on using a procedure based data source - it is more efficient to pass the table of records back to your form than it is to pass a ref cursor. Using a ref cursor, you might as well just using a standard named cursor and loop through your named cursor. The effect is the same (one row returned at a time creating lots of network traffic). Using the table of records is more efficient because the entire data set is returned so network traffic is reduced.
    Hope this helps,
    Craig B-)
    If someone's response is helpful or correct, please mark it accordingly.

  • Reading a ref cursor containing a cursor throws AccessViolationException

    Apologies if this is a known bug. Documenting the simplest case I could find to reproduce it.
    Oracle 10g Release 2 (10.2.0.1.0)
    ODP.NET 2.102.2.10
    Windows XP SP2 32-bit, .Net 2.0.50727
    First, create a simple function that returns a very simple ref cursor:
    =======================
    create or replace function test_get_child_cursor
    return sys_refcursor
    is
         ret_results sys_refcursor;
    begin
         open ret_results for
         select 1 as child_id from dual;
         return ret_results;
    end;
    =======================
    Then try to execute a select that calls this function in ODP.NET:
    =======================
    OracleCommand cmd = conn.CreateCommand();
    cmd.CommandText = "begin open :1 for select 1 as id, test_get_child_cursor() from dual; end;";
    cmd.Parameters.Add("cur", OracleDbType.RefCursor, ParameterDirection.Output);
    cmd.ExecuteNonQuery();
    OracleDataReader reader = ((OracleRefCursor) cmd.Parameters["cur"].Value).GetDataReader();
    while (reader.Read())
    =======================
    Getting the following error when calling reader.Read():
    =======================
    System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
    at Oracle.DataAccess.Client.OpsDac.Read(IntPtr opsConCtx, IntPtr opsErrCtx, IntPtr opsSqlCtx, IntPtr& opsDacCtx, OpoSqlValCtx* pOpoSqlValCtx, OpoMetValCtx* pOpoMetValCtx, OpoDacValCtx* pOpoDacValCtx)
    at Oracle.DataAccess.Client.OracleDataReader.Read()
    =======================
    Is this a supported feature at all in this version of ODP.NET (i.e., reading from a ref cursor that contains other ref cursors)?
    We have several places in our application where we'd like to get cursors containing cursors, so we just want to plan ahead if this is going to be supported.
    Thanks,
    Jeremy

    Hello,
    A bit old, but still relevant:
    Cursor expression & .NET
    Nested cursors are not supported by ODP.NET.
    - Mark

  • STORED PROCEDURE/REF CURSOR: How to output entire buffer

    I wrote a Stored Procedure wherein I use a Cursor to extract multiple
    rows and columns. I then write them into the buffer
    (dmbs_output.put_line). But when I try to capture the entire result
    into an OUT variable, I only get the last buffered line.
    So how do I output the entire buffer- all rows and columns? In other words (maybe), how do I use dbms_output.get_lines() to assign value to an OUT variable?
    Alternatively, using REF CURSOR as OUT variable, I added the following to "CREATE OR REPLACE PROCEDURE ... ()":
    cursor_out_test OUT cursor_test
    But when I tried:
    DEFINE CURSOR TYPE cursor_test IS REF CURSOR RETURN table%ROWTYPE;
    ...or...
    DECLARE TYPE cursor_test IS REF CURSOR RETURN table%ROWTYPE;
    I still got syntax errors.
    In one line, what I am trying to do is break the result array at the database level rather than at the application level.
    Cheers, Bill
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/sqloperations.htm#LNPLS00605

    I did the following:
    OPEN CURSOR x
         LOOP
              FETCH CURSOR x INTO col1, col2
              (EXIT WHEN...)
              variable_line := col1 || col2
         END LOOP
    CLOSE CURSOR
    But after closing this cursor, variable_line contains only the last buffered line. I want all the looped lines (without using associative arrays, nested tables etc). So I guess I am just looking for some way to append data lines- adding chr(10) doesn't work either.
    Cheers, Bill

Maybe you are looking for

  • Sale Order quantity,amount not reduce when raised 1st partialy AR invoice

    Help needed, Please can anyone help .. I came with case that our company policy is to raise Partial AR Invoice on single Sale order. When we generate 1st AR Invoice on Sale order and manually changed qty till this process ok. but when we select 2nd t

  • How to restrict the way to view or print a pdf file

    I am searching for a technique by which I can export a pdf file with following features Prompt a pdf viewer to accept some agreement such that the document can't be viewed until user accepts it Prompt a pdf viewer to select language so that correspon

  • Moving all music off of my ipad

    I am really new to the whole icloud experience.  I am wanting to remove all music, which is 1.9GB, off of my ipad and into icloud.  My question is how do I do this??  Any help is greatly appreciated !!!!

  • Trying to add muzzle flashes to a video

    When I use picture in picture to insert a muzzle flash, only one will appear in the final video. I can see two when I scrub the time line, but only one appears when I preview the video. I cannot figure out why?

  • IPC special scenario

    Hi Gurus, I have a scenario I need to design so please help me with. During in-process inspection I need to perform the following: I have a master recipe with 2 phases of quality inspections. At the 1st phase I'll have 3 samples with certain MICs, le