Sys_refcursor resultset

Hi Masters,
I have created a function which will return result set from emp table. I have to utilize this resultset in another procedure/function. Is it possible?
I have writtne a function like this..
create or replace function test (v_sal in number) return sys_refcursor is
v_cur sys_refcursor;
begin
   open v_cur for select * from emp where sal>=v_sal;
   return v_cur;
end;
SQL> select test(2000) from dual;
6 rows displayed.
I need to use this records to filter in another subprogram? is it possible? Please advise..!!!
Regards
AP

A cursor (reference, explicit or implicit) is NOT a physical result set!
A cursor is like a program - that outputs data. Each fetch call made, executes that cursor, resulting in it finding the next matching row(s) in the database, and returning these to the caller.
A ref cursor is a pointer to the cursor created in server memory. This pointer can then be passed by the code that created the cursor (typically PL/SQL), to the calling code (typically .Net or Java) - enabling that client code to execute that cursor and receive its output data (if any).
Simplistic example:
SQL> create or replace procedure FooProc( nameMask in varchar2, refCur in out sys_refcursor ) is
  2  begin
  3          open refCur for
  4                  select deptno, count(*) from emp where ename like nameMask group by deptno
  5                  order by 2 desc, 1 asc;
  6  end;
  7  /
Procedure created.
SQL>
SQL>
SQL> -- typical use of ref cursor interface from client
SQL> --
SQL> -- client defines a host variable to receive pointer
SQL> var c refcursor
SQL>
SQL> -- client makes PL/SQL call using bind variables
SQL> exec FooProc( 'A%', :c )
PL/SQL procedure successfully completed.
SQL>
SQL> -- client processes cursor pointer (fetch and
SQL> -- display in this case)
SQL> print c
    DEPTNO   COUNT(*)
        20          1
        30          1
SQL>
SQL>
SQL> -- from a PL/SQL perspective a ref cursor would
SQL> -- be handled as follows:
SQL> declare
  2          deptNo          integer;
  3          empCount        integer;
  4          c               sys_refcursor;
  5  begin
  6          FooProc( 'A%', c );
  7          loop
  8                  -- bulk fetch should be used
  9                  fetch c into deptNo, empCount;
10                  exit when c%NotFound;
11
12                  dbms_output.put_line(
13                          'There is/are '||empCount||
14                          ' matching employee(s) in department '||deptNo
15                  );
16          end loop;
17          close c;
18  end;
19  /
There is/are 1 matching employee(s) in department 20
There is/are 1 matching employee(s) in department 30
PL/SQL procedure successfully completed.
SQL>

Similar Messages

  • Is there any provision to view the selected record using SYS_REFCURSOR?

    hi friends ,
    I was using SQL Server . now i am shifting to Oracle . so we are changing the Stored Procedures in SQLServer to Oracle SP's. I have given the structure of procedure given below . If possible , i want to see the output of select statement in the TOAD editor . If any body knows please help me
    CREATE OR REPLACE PROCEDURE PS_AON
    P_STATUS OUT VARCHAR2,
    P_CUR OUT SYS_REFCURSOR
    AS
    BEGIN
    OPEN P_CUR FOR
              select colum1,column2,column3 from Table 1;
    EXCEPTION
                   WHEN OTHERS THEN
                   P_STATUS:=SQLERRM;
    END;
    This is one of the model of stored procedures i am using . And the editor i am using is TOAD 7.3.0 and oracle 9i. Is there any provision to view the selected records by running this procedure in TOAD editor
    thanks & regards

    (assuming you have relatively recent version of TOAD).
    Write a small block to call the procedure (or use Toad's 'execute procedure' option) as in the example below. Note the ':' in front of 'v_cur_out'. When you run the block, TOAD will prompt you for a value / datatype for 'v_cur_out'. Ignore the value, set the datatype to 'Cursor' and click OK. The resultset (if any) will be displayed in the Data Grid window below.
    DECLARE
       v_status VARCHAR2 (32767);
    BEGIN
       ps_aon (v_status, :v_cur_out);
       DBMS_OUTPUT.PUT_LINE ('v_status => ' || v_status);
    END;
    /

  • Issue with sys_refcursor  in oracle  10.2.0.4.0

    hi,
    java is front end application and they want result set to be returned from oracle plsql, for simplicity i am writing code something like below.
    create or replace function fun () retrun sys_refcursor is
    tablename_cur sys_Refcursor;
    begin
    open tablename_cur for select statement;
    return tablename_cur ;
    end;
    its all looks good.. but my client IT person questioned me about not closing cursor..
    i feel it is good way of doing, not closing this type of cursor variable is fine i.e. tablename_cur in this case, does it cause any issues otherwise.. since i am about write not less 300+ such functions and would like to know on this if this is right practice or would it cuase any increase of opened cursor and never closed,.... therafter any performance issues..
    or any other good practive to perform the same task. .. please suggest..
    thanks in advance...

    knowledgespring wrote:
    I assume once sys_Refcursor returned all the rows it get closed automatically... i.e. fetched all the rows from it closes the sys_refcursor.. otherwise provide info.
    according to you, does it mean if they close result set they use in java would result close of sys_refcursor!!.. not before.. may be somthing like
    ResultSet rs = call oracle function which uses sys_refcursor
    rs.close --> does it close sys_refcursor .. (would it open till then??!!!)..
    java developers says we call functions written in oracle... and resultset to be returned.. (They are different team)..I don't know java, but it's correct, the consumer of the cursor is responsible for closing it.
    e.g.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace function test_rc return sys_refcursor is
      2    v_rc sys_refcursor;
      3  begin
      4    open v_rc for 'select * from emp';
      5    return v_rc;
      6* end;
    SQL> /
    Function created.
    SQL> var x refcursor;
    SQL> exec :x := test_rc();
    PL/SQL procedure successfully completed.
    SQL> print x;
         EMPNO ENAME      JOB              MGR HIREDATE          SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17/12/1980        800                    20
          7499 ALLEN      SALESMAN        7698 20/02/1981       1600        300         30
          7521 WARD       SALESMAN        7698 22/02/1981       1250        500         30
          7566 JONES      MANAGER         7839 02/04/1981       2975                    20
          7654 MARTIN     SALESMAN        7698 28/09/1981       1250       1400         30
          7698 BLAKE      MANAGER         7839 01/05/1981       2850                    30
          7782 CLARK      MANAGER         7839 09/06/1981       2450                    10
          7788 SCOTT      ANALYST         7566 19/04/1987       3000                    20
          7839 KING       PRESIDENT            17/11/1981       5000                    10
          7844 TURNER     SALESMAN        7698 08/09/1981       1500          0         30
          7876 ADAMS      CLERK           7788 23/05/1987       1100                    20
          7900 JAMES      CLERK           7698 03/12/1981        950                    30
          7902 FORD       ANALYST         7566 03/12/1981       3000                    20
          7934 MILLER     CLERK           7782 23/01/1982       1300                    10
    14 rows selected.Here, the "print" command of SQL*Plus uses the returned ref cursor to fetch the data back from the database, and when it's done it (behind the scenes) closes the cursor.
    Oracle can't keep track (or even possibly know) of whether a client consumer of a ref cursor has finished fetching the records. Just because all the records may have been fetched, the cursor itself remains open until closed as it contains information about the state of the cursor e.g. whether there is more data to fetch or not.
    {thread:id=886365}

  • How to get resultset from oracle procedure use ejb3

    how to get resultset from oracle procedure use ejb3
    i know oracle procedure should like this
    Create or replace PROCEDURE resultset_test(
    aaa IN NUMBER,
    bbb OUT sys_refcursor) ....
    but what s the ejb3 scripts looks like? please give me an example or link~
    ths

    - there are no EJB3 scripts, only compiled application code
    - the part of the EJB spec that deals with databases is called the Java Persistence API, but likely you are just looking for the JDBC API.
    Now you should know what to Google to get your "example script": "java jdbc oracle procedure"

  • Output SYS_REFCURSOR when cursor structure is not known

    If i have a variable of type "SYS_REFCURSOR".
    This cursor will be passed to various procedures which open various recordset for that cursor, with various number of columns in cursor.
    How to output cursor all columns?
    1. Maybe java will have metadata information for cursor and can output the resultset of cursor. If so, then this is ok to choose this solution. also VbScript is ok, if it can help.
    2. Maybe one can create table temporarily based on the cursor. And table objects have meta data in oracle system tables, so i can output all cursor data.
    3. Maybe i can use so called try-catch clauses techique to help somehow. For example
    Try
      fetch cur1 into varchar2_var1, .., varchar2_var5
    catch (if error)
          try
              fetch cur1 into varchar2_var1, .., varchar2_var4
    Till we know how many fields there are.
    somehow this way to go next4. Maybe execute immediate can help somehow.

    If you're not in 11g and you at least have some options of structures you want to try and fetch to, you can make use of the rowtype_mismatch exception by catching it and trying to fetch into a different structure until you find it, by nesting PL/SQL begin...exception...end; blocks.
    You won't lose rows if you attempt to fetch into the wrong structure.
    In the example below I try to fetch into a type with 2 columns and it fails then I attempt again against a 3-column type.
    Note that the column type mismatch on implicit conversions will throw other exceptions as ORA-06504 or ORA-01722 for example.
    Connected to Oracle Database 10g Enterprise Edition Release 10.2.0.4.0
    Connected as fsitja
    SQL> set serveroutput on
    SQL>
    SQL> DECLARE
      2    cur SYS_REFCURSOR;
      3    TYPE t_rec1 IS RECORD(
      4      col1 NUMBER,
      5      col2 VARCHAR2(100));
      6    v_rec1 t_rec1;
      7    TYPE t_rec2 IS RECORD(
      8      col3 NUMBER,
      9      col4 VARCHAR2(100),
    10      col5 VARCHAR2(100));
    11    v_rec2 t_rec2;
    12  BEGIN
    13    OPEN cur FOR
    14      SELECT 1 col3, 'a' col4, 'b' col5 FROM dual;
    15    FETCH cur
    16      INTO v_rec1;
    17    dbms_output.put_line('REC1.COL1: ' || v_rec1.col1);
    18    dbms_output.put_line('REC1.COL2: ' || v_rec1.col2);
    19  EXCEPTION
    20    WHEN rowtype_mismatch THEN
    21      FETCH cur
    22        INTO v_rec2;
    23      dbms_output.put_line('REC2.COL3: ' || v_rec2.col3);
    24      dbms_output.put_line('REC2.COL4: ' || v_rec2.col4);
    25      dbms_output.put_line('REC2.COL5: ' || v_rec2.col5);
    26  END;
    27  /
    REC2.COL3: 1
    REC2.COL4: a
    REC2.COL5: b
    PL/SQL procedure successfully completed
    SQL>

  • Need to obtain updateable ResultSet via call to PL/SQL function

    I'm using JDBC and the Oracle JDBC driver to call a PL/SQL function that returns a SYS_REFCURSOR. I do this via a CallableStatement object and then cast the output parameter to a ResultSet object. However, I want this ResultSet object I end up with to be updateable. The following code throws an exception stating "Invalid operation for read only resultset: updateString ":
    cstmt2 = con.prepareCall("{? = call get_upload_entry_for_update(?)}",
                             ResultSet.TYPE_FORWARD_ONLY,
                             ResultSet.CONCUR_UPDATABLE);
    cstmt2.registerOutParameter(1, OracleTypes.CURSOR);
    cstmt2.setInt(2, newUploadId);
    cstmt2.execute();
    rs = (ResultSet) cstmt2.getObject(1);
    rs.next();
    rs.updateString("UPLOAD_FILENAME", fileName);
    // . . .So even though, I create the CallableStatement such that ResultSets should be updateable, it's not allowing me to do any updates. Also, in case you're wondering, inside the PL/SQL function, the query on which the cursor is based is a select statement which does specify "for update" at the end.
    I can get it to work as follows using a Statement object that executes the SELECT statement directly instead of a CallableStatement that executes a PL/SQL function:
    Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    rs = stmt.executeQuery("select UPLOAD_FILENAME, UPLOAD_FILE from rf_upload where upload_id = "+newUploadId+" for update");
    rs.next();
    rs.updateString("UPLOAD_FILENAME", fileName);
    //. . . Although this works, the project I'm working has a goal to encapsulate all SQL into Functions and Stored Procedures so I'd like to get it working that way instead.
    So the bottom-line question is: Using the Oracle JDBC driver, how can I call a PL/SQL function in such a way that I can obtain an updateable ResultSet object?
    Thanks for any suggestions. I'd be happy to clarify anything that's unclear.

    Hmmm...
    I'm still scratching my head about this one, just not sure it's doable, but I'll point out something, maybe it will give you a clue...
    In your code, you have:
    cstmt2 = con.prepareCall("{? = call get_upload_entry_for_update(?)}",
                             ResultSet.TYPE_FORWARD_ONLY,
                             ResultSet.CONCUR_UPDATABLE);I don't think the ResultSet parameters do anything towards your goal of getting an updatable result set via the returned cursor, those parameters affect the result set produced if you were to call:
    ResultSet rs2 = cstmt2.executeQuery();and not the result set generated by:
    rs = (ResultSet) cstmt2.getObject(1);Futhermore, while the "FOR UPDATE" is almost certainly something you want to do, it also doesn't affect the cursor (I think) but merely locks the affected rows in the DB.
    You might try calling rs.getType() and rs.getConcurrency() on the ResultSet you get from getObject, though I suspect they'll merely confirm the bad news that the cursor your getting back isn't right...
    You also might try the Oracle-specific getCursor call:
    rs = ((OracleCallableStatement)cstmt2).getCursor (1)instead of getObject, though I don't think it will help...
    I've been curious enough to dig around through most of my handy references and Oracle's docs and MetaLink and come up mostly empty, although almost 5 years ago Oracle Support said:
    " Reference Cursors from a pl/sql stored procedure are not updateable in any language."

  • Sys_refcursor procedure parameters in out

    Hi,
    I have created a procedure that receive the SQL statment in VARCHAR" datatype parameters and return the Resultset into a refcursor :
    create or replace
    procedure my_test(VAL1 in number, val2 in number, val3 in number, val4 in VARCHAR2, vla5 out nocopy SYS_REFCURSOR )
    is
    begin
      open vla5 for 'select * FROM (select x_x.*  ,rownum rn  FROM ('||val4 ||') x_x where rownum <= '|| to_char(val3)||' ) where rn >='|| to_char(val2);
    end;I like to pass and receive the val4 and val5 in one parameters :
    procedure my_test(VAL1 in number, val2 in number, val3 in number, val4 in out nocopy SYS_REFCURSOR )I like to pass the SQL statment in VARCHAR2 datatype to my procedure and return the result in the same variable parameters.
    I don't know if my english was understand, but could you please help me to find a solution?
    thanks a lot.
    Calà Salvatore

    Can we have more detail please?
    A sys_refcursor is not a SQL statement that you can add predicates to. So not possible to combine the two arguments. Not at all.
    To receive a refcursor and try to do it doesn't make sense.
    See Refcursor 101 thread:
    PL/SQL 101 : Understanding Ref Cursors
    If you want to receive a SQL statement as a VARCHAR2/CLOB/LONG and you want to wrap it with further predicates then you can do that just with string manipulation - as you're doing.
    However, if you do receive a sql statement as a string and want to wrap it with a select and further predicates, you should use binds for the predicate values not string concatenation of literals which is likely to be poorly performant and a possible security issue (also see DBMS_ASSERT).
    Edited by: DomBrooks on Nov 9, 2010 11:00 AM

  • OUT parameter with NOCOPY hint of type SYS_REFCURSOR

    Hi,
    I am having a procedure which returns a set of 100+ records (each record having 10+ columns) through a OUT parameter of type SYS_REFCURSOR.
    These output records are used in JAVA code for fecthing the resultset and process data.
    Will it make any difference in performance if I use NOPCOPY compiler hint in this procedure (especially I am interested in the interaction between JAVA and PLSQL, with and without NOCOPY parameter).
    Thanks.
    Edited by: user2946813 on Mar 25, 2012 9:15 PM

    user2946813 wrote:
    Hi RP,
    Thanks for the answer.
    So the PLSQL OUT parameter of type SYS_REFCURSOR would be passing just a reference (memory address) to JAVA.
    This behavior is same with or without NOCOPY. Is my understanding correct?
    Thanks.Yes. A ref cursor is just a pointer to a query, not a result set of data. Using NOCOPY or not is pointless (excuse the pun) because, no matter how much data is going to get returned, the pointer itself is no smaller or larger in size, and thus using NOCOPY won't improve performance or save resources.
    {thread:id=886365}

  • How to return SQL query results as resultset

    I am developing a site in ASP to support back end as oracle or SQL server.
    In SQL Server, from stored procedure it is possible to return resultset by writing sql query in procedure using input parameters as filters (where condition).
    Is there a way to return a resultset from oracle procedures or functions.

    http://asktom.oracle.com/~tkyte/ResultSets/index.html
    In 9i or above you no longer need to define your own weak ref cursor type in a package spec, you can use the built-in SYS_REFCURSOR.

  • Getting column names from SYS_REFCURSOR

    Hi everybody, i have a SYS_REFCURSOR in a procedure. And i open it and fetch cursor to a record as follows:
    OPEN curgroup FOR vexpr2;
    LOOP
    FETCH curgroup INTO recType;
    END LOOP;
    recType is a Record, has two variables. Anyway, the question is can i get the column names from refcursor?
    like recType.COLUMN1 (Column1 is not a record variable ) ????
    or is there anything else to perform this operation?

    Hi,
    Despite what Billy states it is very possible to get the column names from a weak ref cursor, or describe a ref cursor with PL/SQL. It has been possible since 8i, it just relies on the little known fact that a ref cursor in PL/SQL translates directly to a ResultSet in Java so we can use a tiny JSP in the DB.
    Here is the link to the completely free, Open Source code which allows you to do this: [XUTL_REFCURSOR|http://www.chrispoole.co.uk/apps/xutlrefcursor.htm]
    And a little example:
    SQL> variable scott_cursor refcursor
    SYS@ORA10GR2
    SQL> begin
      2  open :scott_cursor for select * from scott.emp;
      3  end;
      4  /
    PL/SQL procedure successfully completed.
    SYS@ORA10GR2
    SQL> begin
      2  xutl_refcursor.describe_columns(:scott_cursor);
      3  end;
      4  /
    PL/SQL procedure successfully completed.
    SYS@ORA10GR2
    SQL> select col_name from xutl_described_columns;
    COL_NAME
    EMPNO
    ENAME
    JOB
    MGR
    HIREDATE
    SAL
    COMM
    DEPTNO
    SYS@ORA10GR2
    SQL> print :scott_cursor
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17/12/1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN        7698 20/02/1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN        7698 22/02/1981 00:00:00       1250        500         30
          7566 JONES      MANAGER         7839 02/04/1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN        7698 28/09/1981 00:00:00       1250       1400         30
          7698 BLAKE      MANAGER         7839 01/05/1981 00:00:00       2850                    30
          7782 CLARK      MANAGER         7839 09/06/1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 19/04/1987 00:00:00       3000                    20
          7839 KING       PRESIDENT            17/11/1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 08/09/1981 00:00:00       1500          0         30
          7876 ADAMS      CLERK           7788 23/05/1987 00:00:00       1100                    20
          7900 JAMES      CLERK           7698 03/12/1981 00:00:00        950                    30
          7902 FORD       ANALYST         7566 03/12/1981 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 23/01/1982 00:00:00       1300                    10
    14 rows selected.
    SYS@ORA10GR2
    SQL>As the demo shows describing the ref cursor does not affect the cursor in any way, it is not selected from. It is not converted into a DBMS_SQL cursor and can be passed to a front end.
    [XUTL_REFCURSOR|http://www.chrispoole.co.uk/apps/xutlrefcursor.htm] is designed to have exactly the same output and uses the same return type as DBMS_SQL DESCRIBE COLUMNS, to enable pre-existing code that uses that API to be quickly re-used.
    HTH
    Chris

  • Returning rowcount and resultset from stored procedure

    Hello,
    In SQL Server you can return multiple resultsets from stored procedure by simple SELECT statement. But in Oracle, you have to use SYS_REFCURSOR.
    Sample code:
    CREATE OR REPLACE PROCEDURE sp_resultset_test IS
    t_recordset OUT SYS_REFCURSOR
    BEGIN
    OPEN t_recordset FOR
    SELECT * FROM EMPLOYEE;
    END sp_resultset_test;
    Is there any other way in Oracle 10 or 11 ?
    Thank You.

    What is the requirement? Oracle is far more flexible than SQL-Server... with numerous features that do not exist in SQL-Server. (Fact)
    One of the biggest mistakes you can make is to treat Oracle like SQL-Server... trying to match feature A1 in SQL-Server to feature B3 in Oracle.
    Does not work that way.. rather then stick to SQL-Server as SQL-Server does SQL-Server specific features far better than Oracle.
    So instead of trying to map what a T-SQL stored proc to do to an Oracle ref cursor (even to the extent of using that very silly sp_ prefix to name the proc), tell us the problem and requirements... That way we can tell you what Oracle features and options are best used to solve that problem - instead of competing in some unknown feature comparison event with SQL-Server.

  • Viewobject - Stored Procedure with sys_refcursor out

    Hi,
    I have been trying to call an Oracle stored procedure which returns sys_refcursor as an out parameter.
    Even though I register out parameter in callStoreFunction method, I am getting "PLS-00306: wrong number or types of arguments in call".
    You can find piece of codes below.
    Could you please help?
    Thanks in advance.
    Stored Procedure;*
    CREATE OR REPLACE PROCEDURE SP_GET_PRODUCT_DETAIL_BY_ID(
    ID_in IN NUMBER,
    p_product_refcur OUT SYS_REFCURSOR
    IS
    BEGIN
    OPEN p_product_refcur FOR SELECT * FROM PRODUCT_DETAIL WHERE ID = ID_in;
    END SP_GET_PRODUCT_DETAIL_BY_ID;
    Java Code*
    The code that calls function method;
    ResultSet rs = (ResultSet)callStoredFunction(OracleTypes.CURSOR,"SP_GET_PRODUCT_DETAIL_BY_ID(?)",new Object[]{new Number(3)});
    Call function method;
    protected Object callStoredFunction(int sqlReturnType, String stmt, Object[] bindVars) {
    CallableStatement st = null;
    try {
    System.out.println("222222");
    // 1. Create a JDBC CallabledStatement
    st = getDBTransaction().createCallableStatement("begin ? := " + stmt + ";end;", 0);
    // 2. Register the first bind variable for the return value
    st.registerOutParameter(1, sqlReturnType);
    if (bindVars != null) {
    // 3. Loop over values for the bind variables passed in, if any
    for (int z = 0; z < bindVars.length; z++) {
    // 4. Set the value of user-supplied bind vars in the stmt
    st.setObject(z+2, bindVars[z]);
    // 5. Set the value of user-supplied bind vars in the stmt
    st.executeUpdate();
    // 6. Return the value of the first bind variable
    return st.getObject(1);
    } catch (SQLException e) {
    e.printStackTrace();
    throw new JboException(e);
    } finally {
    if (st != null) {
    try {
    // 7. Close the statement
    st.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }

    Hi mate,
    Sorry about that. My Jdev version is 11.1.2.3.0.
    The use case is that I am trying to call a SP from a VO which is triggered from App Module. I have a bind parameter in App Module for SP input, but at the moment I am using a static value for test purpose.
    I am able to make a call from App Module to SP via VO but got an error as I am calling with wrong parameters.
    Stored Procedure;_
    CREATE OR REPLACE PROCEDURE SP_GET_PRODUCT_DETAIL_BY_ID(
       ID_in IN NUMBER,
       p_product_refcur OUT SYS_REFCURSOR
    IS
    BEGIN
       OPEN p_product_refcur FOR SELECT * FROM PRODUCT_DETAIL WHERE ID = ID_in;
    END SP_GET_PRODUCT_DETAIL_BY_ID;
    Java Code_
    The code that calls function method;
    ResultSet rs = (ResultSet)callStoredFunction(OracleTypes.CURSOR,"SP_GET_PRODUCT_DETAIL_BY_ID(?)",new Object[]{new Number(3)});
    Call function method;
    protected Object callStoredFunction(int sqlReturnType, String stmt, Object[] bindVars) {
       CallableStatement st = null;
       try {
          // 1. Create a JDBC CallabledStatement
          st = getDBTransaction().createCallableStatement("begin ? := " + stmt + ";end;", 0);
          // 2. Register the first bind variable for the return value
          st.registerOutParameter(1, sqlReturnType);
          if (bindVars != null) {
             // 3. Loop over values for the bind variables passed in, if any
             for (int z = 0; z < bindVars.length; z++) {
                // 4. Set the value of user-supplied bind vars in the stmt
                st.setObject(z+2, bindVars[z]);
          // 5. Set the value of user-supplied bind vars in the stmt
          st.executeUpdate();
          // 6. Return the value of the first bind variable
          return st.getObject(1);
          } catch (SQLException e) {
             e.printStackTrace();
             throw new JboException(e);
          } finally {
             if (st != null) {
                try {
                   // 7. Close the statement
                   st.close();
                } catch (SQLException e) {
                   e.printStackTrace();
    The exact error;
    java.sql.SQLException: ORA-06550: line 1, column 14:
    PLS-00306: wrong number or types of arguments in call to 'SP_GET_PRODUCT_DETAIL_BY_ID'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignoredThanks alot.

  • Querying PL/SQL function which returns SYS_REFCURSOR

    Hello:
    I have a PL/SQL function with return type of SYS_REFCURSOR.
    In SQLPlus, I can query it either as
    var c refcursor
    exec :c := func(...)
    print c
    or
    select func(...) from dual;
    Running the latter in Eclipse 3.3 with oracle DTP extensions installed gives me OracleResultSetImpl object in the SQL Results view.
    Can the code be a little smarter and recognize that a sql query may return "indirect" resultset?
    Regards,
    Ernest

    This is noted; will be the interface better to handle the return values. Thanks

  • [perl] How call function/procedure that returns SYS_REFCURSOR type?

    I've got some simple procedure which returns record(s):
    CREATE OR REPLACE PROCEDURE "GET_SYS_DATE"
    RESULTSET IN OUT SYS_REFCURSOR
    IS
    BEGIN
         OPEN RESULTSET FOR
              SELECT SYSDATE FROM DUAL;
    END;
    In perl i invoke it with somthing like this:
    my $ret;
    my $s= "BEGIN GET_SYS_DATE(:1); END;";
    my $sth = $dbh->prepare($s);
    $sth->bind_param_inout(1, \$ret, 0 { TYPE => XXX}); # tried to use many DBD::SQL_* types (SQL_ROW, SQL_REF, etc.)
    $sth->execute(); #... but without luck
    I always get:
    DBD::ODBC::st execute failed: [Oracle][ODBC][Ora]ORA-06550: line 1, column 7:
    PLS-00306: wrong number or types of arguments in call to 'GET_SYS_DATE'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    Of course if i use other datatype in SP (e.g. VARCHAR2) and bind it as SQL_VARCHAR it works well... Moreover, if i use DBD::Oracle and bind it as ORA_RSET type it also works.
    Is it possible that ODBC doesn't know SYS_REFCURSOR type? Then, is there any way to call SP and retrieve cursor from perl without using DBD::Oracle?
    Or, if it is possible, then how to retrieve that cursor and data stored within it? Any help?

    Hi,
    I have not one eensy teensy bit of knowledge about PERL, other than how to spell it.
    I do however, know about ref cursors, and ODBC, so maybe this will help.
    ODBC has nothing for REF CURSOR built in. ODBC is made to the lowest common denoninator of databases, and a refcur is an Oracle thing. So, what that means is that you can't BIND anythign to the ref cursor, as there is no appropriate ODBC type to bind.
    Does that mean you can't call a refcur via ODBC? No, it doesnt.
    What happens is that Oracle's ODBC driver kinda "magically" goes out behind the scenes and describes the procedure or pacakge to determine if any of the parameters are ref cursors, and if so automatically sets up the bind for them.
    Here's a complete working example using VB and ADO rather than PERL, but maybe you can port it over and get it working. Note that the proc takes two params, but we only bind one (for the IN number)
    Hope it helps,
    Greg
    'create or replace package testrefcur as
    '  type mycur is ref cursor;
    ' procedure getemps(dno in number, ecur out mycur);
    ' end;
    'create or replace package body testrefcur as
    'procedure getemps(dno in number, ecur out mycur) is
    '  begin
    '     open ecur for select * from emp where deptno = dno;
    '  end;
    'end;
    Private Sub Command1_Click()
    Dim con As New ADODB.Connection
    Dim cmd As New ADODB.Command
    Dim rst As New ADODB.Recordset
    strcnn = "dsn=orcl;uid=scott;pwd=tiger"
    con.Open strcnn
    cmd.CommandText = "{call testrefcur.getemps(?)}"
    Set cmd.ActiveConnection = con
    Set param1 = cmd.CreateParameter("param1", adNumeric, adParamInput, 4)
    param1.Value = 10
    param1.Precision = 4
    cmd.Parameters.Append param1
    Set rst = cmd.Execute  
    While Not rst.EOF
    strrslt = strrslt & rst.Fields("ename").Value & " "
    rst.MoveNext
    Wend
    MsgBox strrslt
    End Sub

  • Returning resultset from procedure...or pkg

    I am a newbie to Oracle but am steeped in MSSQL. I am accustomed to using a procedure to execute and produce a result set as its output from various input parameters thus keeping query complexity and details as a part of the database tier.
    Is there a best practice in Oracle that provides this capability? Is the 'ref cursor' the correct container to hold the recordset data (usually combined from various base tables...counts and sums for reports etc) and how should it be returned to a calling application (web page) to be iterated through? Perhaps as an output parameter?
    Thank you for helping with such a basic problem.

    Yes you would use a ref cursor, though it does not hold the results anywhere, they are fetched as needed, which is why it scales well.
    Re: OPEN cursor for large query
    Re: cursor ,inner join
    You can return a ref cursor from a function or procedure, it would be no different in a package.
    SQL> create or replace function f (p_deptno in number)
      2  return sys_refcursor as
      3    c sys_refcursor;
      4  begin
      5    open c for
      6      select empno, ename, job, sal from emp
      7        where deptno = p_deptno;
      8    return c;
      9  end;
    10  /
    Function created.
    SQL> var c refcursor
    SQL> exec :c := f(10)
    PL/SQL procedure successfully completed.
    SQL> print c
    EMPNO ENAME      JOB          SAL
      7782 CLARK      MANAGER     2450
      7839 KING       PRESIDENT   5000
      7934 MILLER     CLERK       1300
    SQL> create or replace procedure p
      2    (p_deptno in number, p_c out sys_refcursor)
      3  as
      4  begin
      5    open p_c for
      6      select empno, ename, job, sal from emp
      7        where deptno = p_deptno;
      8  end;
      9  /
    Procedure created.
    SQL> exec p(30, :c)
    PL/SQL procedure successfully completed.
    SQL> print c
    EMPNO ENAME      JOB          SAL
      7499 ALLEN      SALESMAN    1600
      7521 WARD       SALESMAN    1250
      7654 MARTIN     SALESMAN    1250
      7698 BLAKE      MANAGER     2850
      7844 TURNER     SALESMAN    1500
      7900 JAMES      CLERK        950
    6 rows selected.
    SQL>There are examples how to reference them in other languages here, note this was pre-9i when the built in sys_refcursor type was provided.
    http://asktom.oracle.com/tkyte/ResultSets/index.html

Maybe you are looking for