Error Returning REF CURSOR

I'm trying to return a REF CURSOR from a function and get the following error:
ORA-00932: inconsistent datatypes: expected CURSER got NUMBER
ORA-06512: at "CERTS.JIMMY", line 17
ORA-06512: at line 10
Here is my function:
CREATE OR REPLACE PACKAGE jimmy
AS
TYPE refc IS REF CURSOR
RETURN equipment%rowtype;
FUNCTION getresults(p_ssan_in IN equipment.ssan%TYPE,
                         p_type_in IN equipment.equip_type%TYPE)
     RETURN refc;
END jimmy;
CREATE OR REPLACE PACKAGE BODY jimmy
AS
FUNCTION getresults( p_ssan_in IN equipment.ssan%TYPE,
                              p_type_in IN equipment.equip_type%TYPE)
RETURN refc
IS
l_cursor refc;
isretired equipment.retired%TYPE := 'N';
qry varchar2(100) := 'SELECT * ' ||
                              'FROM equipment ' ||
                              'WHERE ssan = :b1 ' ||
                              'AND equip_type = :b2 ' ||
                              'AND retired = :b3';
BEGIN
EXECUTE IMMEDIATE qry
     INTO l_cursor
     USING p_ssan_in, p_type_in, isretired;
RETURN l_cursor;
END getresults;
END jimmy;
The data types for the parameters are all varchar2. I don't know why it says it is returning a number.

I tried your suggestion:
BEGIN
OPEN l_cursor
     FOR qry
     USING p_ssan_in, p_type_in, isretired;
RETURN l_cursor;
END getresults;
But I get an error:
PLS-00455: cursor 'L_CURSOR' cannot be used in dynamic SQL OPEN statement

Similar Messages

  • MS Access, ODBC and SPs returning ref cursor

    I have some functions and procedures in a package returning ref cursors that work fine in my C++ batch applications. I would like for the GUI to be able to call these as well.
    Unfortunately, we are using Access as the front end (for now), and we have not been able to get the ref cursors to work. Is this supported? We are using Oracle 8.0.5 on Solaris, and our clients is Access 97 on NT using Intersolv's ODBC driver.
    My procedure looks something like:
    package jec is
    procedure open_sale_cur(
    p_client_id number,
    sale_curvar out sale_curtype)
    is begin
    open sale_curtype for select ... ;
    end;
    end;
    And the Access code looks like this:
    strSql = "begin jec.open_sale_cur(27, ?); end;"
    qdfTemp = conMain.CreateQueryDef("", strSql)
    qdfTemp.Parameters(0).Direction = dbParamOutput
    qdfTemp.Execute()
    This is the error when Execute() is called:
    PLS-00306: wrong number or types of arguments in call to 'OPEN_SALE_CUR'
    I am not an Access programmer; I am simply passing along this information. Any help would be greatly appreciated.

    We tried the {call...} syntax originally, but when we use it, we get an Oracle syntax error for the statement
    SELECT * FROM {call ...}
    Apparently Access prepends "SELECT..." before passing the SQL text to Oracle.
    This is also the case for procedures with normal scalars, such as numbers, returned as OUT values. When we use anon PL/SQL syntax and "?" placeholders with such procedures, they work. When we use {call ...} syntax or omit OUT placeholders, they do not.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Justin Cave ([email protected]):
    I suspect that you want to simply execute the statement
    strSql = {call open_sale_cur( 27 )}
    The ODBC driver will automatically figure out that there's an output parameter which is a ref cursor and return that as the result set. Note that you may want to download the latest 8.0.5 ODBC driver (8.0.5.10 I believe) if there are any problems.
    Justin<HR></BLOCKQUOTE>
    null

  • Problem with XSU when trying to execute pl/sql package returning ref cursor

    Hi,
    I'm exploring xsu with 8i database.
    I tried running sample program which I took from oracle
    documentation. Here is the details of these.
    ------create package returning ref cursor---
    CREATE OR REPLACE package testRef is
         Type empRef IS REF CURSOR;
         function testRefCur return empRef;
    End;
    CREATE OR REPLACE package body testRef is
    function testRefCur RETURN empREF is
    a empREF;
    begin
    OPEN a FOR select * from emp;
    return a;
    end;
    end;
    ---------package successfully created-----
    Now I use java program to generate xml data from ref cursor
    ------------java program ----------
    import org.w3c.dom.*;
    import oracle.xml.parser.v2.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.xml.sql.query.OracleXMLQuery;
    import java.io.*;
    public class REFCURt
    public static void main(String[] argv)
    throws SQLException
    String str = null;
    Connection conn = getConnection("scott","tiger"); //
    create connection
    // Create a ResultSet object by calling the PL/SQL function
    CallableStatement stmt =
    conn.prepareCall("begin ? := testRef.testRefCur();
    end;");
    stmt.registerOutParameter(1,OracleTypes.CURSOR); // set
    the define type
    stmt.execute(); // Execute the statement.
    ResultSet rset = (ResultSet)stmt.getObject(1); // Get the
    ResultSet
    OracleXMLQuery qry = new OracleXMLQuery(conn,rset); //
    prepare Query class
         try
    qry.setRaiseNoRowsException(true);
    qry.setRaiseException(true);
    qry.keepCursorState(true); // set options (keep the
    cursor alive..
         System.out.println("..before printing...");
    while ((str = qry.getXMLString())!= null)
    System.out.println(str);
         catch(oracle.xml.sql.OracleXMLSQLNoRowsException ex)
    System.out.println(" END OF OUTPUT ");
    qry.close(); // close the query..!
    // qry.close(); // close the query..!
    // Note since we supplied the statement and resultset,
    closing the
    // OracleXMLquery instance will not close these. We would
    need to
    // explicitly close this ourselves..!
    stmt.close();
    conn.close();
    // Get the connection given the user name and password..!
    private static Connection getConnection(String user, String
    passwd)
    throws SQLException
    DriverManager.registerDriver(new
    oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection
    ("jdbc:oracle:thin:@xxxx:1521:yyyy",user,passwd);
    return conn;
    when I ran the program after successful compilation,I got the
    following error
    ==========
    Exception in thread "main" oracle.xml.sql.OracleXMLSQLException:
    1
    at oracle.xml.sql.core.OracleXMLConvert.getXML(Compiled
    Code)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:263)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:217)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:194)
    at REFCURt.main(Compiled Code)
    ============================
    Can anybody tell me why I'm getting this error.Am I missing any
    settings?
    thanks

    We are using 8.1.7 Oracle db with latest xdk loaded.
    am I missing any settings?

  • Call ref cursor functions in function also returning ref cursor?

    In 10g database, I have several functions and procedures, some packaged, that return ref cursors. These work as expected.
    Is there a way to call one or more of these in a new function and return another ref cursor?
    I know this doesn't work, but I hope it conveys the idea.
    function f_get_order_lines
       return sys_refcursor -- or defined ref cursor
    is
      v_ords orders_rcr;
      v_lines lines_rcr;
      x sys_refcursor;
    begin
      v_ords := f_get_orders;
      for rec in v_ords
       loop
        v_lines := f_get_lines;
       ... do other work here...
      end loop;
    return x;
    end;

    Pipelined table functions might do the trick for you, depending you your requirements and the transformations you need to make:
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/tuning.htm#sthref2345

  • Call to Oracle stored procedure that returns ref cursor doesn't work

    I'm trying to use an OData service operation with Entity Framework to call an Oracle stored procedure that takes an number as an input parameter and returns a ref cursor. The client is javascript so I'm using the rest console to test my endpoints. I have been able to successful call a regular Oracle stored procedure that takes a number parameter but doesn't return anything so I think I have the different component interactions correct. When I try calling the proc that has an ref cursor for the output I get the following an error "Invalid number or type of parameters". Here are my specifics:
    App.config
    <oracle.dataaccess.client>
    <settings>
    <add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursor.P_RESULTS" value="implicitRefCursor bindinfo='mode=Output'" />
    <add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.0" value="implicitRefCursor metadata='ColumnName=WINDFARM_ID;BaseColumnName=WINDFARM_ID;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Number;ProviderType=Int32'" />
    <add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.1" value="implicitRefCursor metadata='ColumnName=STARTTIME;BaseColumnName=STARTTIME;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
    <add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.2" value="implicitRefCursor metadata='ColumnName=ENDTIME;BaseColumnName=ENDTIME;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
    <add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.3" value="implicitRefCursor metadata='ColumnName=TURBINE_NUMBER;BaseColumnName=TURBINE_NUMBER;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
    <add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.4" value="implicitRefCursor metadata='ColumnName=NOTES;BaseColumnName=NOTES;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
    <add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYWINDFARMID.RefCursorMetaData.P_RESULTS.Column.5" value="implicitRefCursor metadata='ColumnName=TECHNICIAN_NAME;BaseColumnName=TECHNICIAN_NAME;BaseSchemaName=PGDATA_WC;BaseTableName=WORKORDERS;NATIVEDATATYPE=Varchar2;ProviderType=Varchar2'" />
    <add name="PGDATA_WC.ODATAPOC.GETWORKORDERSBYID.RefCursor.P_RESULTS" value="implicitRefCursor bindinfo='mode=Output'" />
    </settings>
    OData Service Operation:
    public class OracleODataService : DataService<OracleEntities>
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
    // Examples:
    config.SetEntitySetAccessRule("*", EntitySetRights.All);
    config.SetServiceOperationAccessRule("GetWorkOrdersByWindfarmId", ServiceOperationRights.All);
    config.SetServiceOperationAccessRule("CreateWorkOrder", ServiceOperationRights.All);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    [WebGet]
    public IQueryable<GetWorkOrdersByWindfarmId_Result> GetWorkOrdersByWindfarmId(int WindfarmId)
    return this.CurrentDataSource.GetWorkOrdersByWindfarmId(WindfarmId).AsQueryable();
    [WebGet]
    public void CreateWorkOrder(int WindfarmId)
    this.CurrentDataSource.CreateWorkOrder(WindfarmId);
    Here is the stored procedure:
    procedure GetWorkOrdersByWindFarmId(WINDFARMID IN NUMBER,
    P_RESULTS OUT REF_CUR) is
    begin
    OPEN P_RESULTS FOR
    select WINDFARM_ID,
    STARTTIME,
    ENDTIME,
    TURBINE_NUMBER,
    NOTES,
    TECHNICIAN_NAME
    from WORKORDERS
    where WINDFARM_ID = WINDFARMID;
    end GetWorkOrdersByWindFarmId;
    I defined a function import for the stored procedure using the directions I found online by creating a new complex type. I don't know if I should be defining the input parameter, WindfarmId, in my app.config? If I should what would that format look like? I also don't know if I'm invoking the stored procedure correctly in my service operation? I'm testing everything through the rest console because the client consuming this information is written in javascript and expecting a json format. Any help is appreciated!
    Edited by: 1001323 on Apr 20, 2013 8:04 AM
    Edited by: jennyh on Apr 22, 2013 9:00 AM

    Making the change you suggested still resulted in the same Oracle.DataAccess.Client.OracleException {"ORA-06550: line 1, column 8:\nPLS-00306: wrong number or types of arguments in call to 'GETWORKORDERSBYWINDFARMID'\nORA-06550: line 1, column 8:\nPL/SQL: Statement ignored"}     System.Exception {Oracle.DataAccess.Client.OracleException}
    I keep thinking it has to do with my oracle.dataaccess.client settings in App.Config because I don't actually put the WindfarmId and an input parameter. I tried a few different ways to do this but can't find the correct format.

  • Calling stored proc from java to return ref cursor

    Hi All,
    We have a requirement to display all the records from a table on a JAVA screen. Due to some constraints, we have to write the query in the stored proc. We are trying to return a result set from the stored proc to the java code by using a ref cursor. Please refer to the code below.
    Following is the PL/SQL proc ?
    procedure sp_user_course2(v1 OUT ref_cursor, persid in varchar2) as
    begin
    open v1 for
    SELECT lrn_exp_id, crs_name FROM emp_crs
    WHERE personid = persid;
    end;
    Here ref_cursor is of TYPE REF CURSOR declared in the package specification.
    The java code is ?
    Callable stmt = conn.prepareCall("call sp_user_course2(?,?)");
    stmt.registerOutParameter(1,OracleTypes.CURSOR);
    stmt.setString(2,emplId);
    stmt.execute();
    OracleCallableStatement tstmt = (OracleCallableStatement) stmt;
    ResultSet rs = tstmt.getCursor (1);
    When I run the program, I get the following error (at stmt.execute()):
    [Oracle][ODBC][Ora]ORA-06553: PLS-306: wrong number or types of arguments in call to 'SP_USER_COURSE2' 6553
    Can anyone tell me what could be the problem with this code? I have read somewhere that REF CURSOR feature is available from Oracle 9i onwards. If so, then, is there any workaround for mapping REF CURSOR to Resultsets in Oracle 8i?

    These may help
    http://www.google.co.uk/search?q=jdbc+OracleTypes.CURSOR+tutorial

  • Error retrieving REF CURSOR

    Hi,
    I have a problem retrieving a ResultSet from a REF CURSOR. I am using and OCI driver and Oracle 9i.
    Mi Code is like this:
    public static void main(String[] args) throws ClassNotFoundException,
    SQLException {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(
    "jdbc:oracle:oci:@XXXXX", "login", "password");
    CallableStatement cs = conn.prepareCall("{?=call package.name(P_CODIGO => ?)}");
    cs.registerOutParameter(1,OracleTypes.CURSOR);
    cs.setInt(2,16782);
    cs.executeQuery();
    ResultSet result = ((OracleCallableStatement)cs).getCursor(1);
    result.next();
    ResultSetMetaData rsmd = result.getMetaData();
    for(int i = 0; i < rsmd.getColumnCount();i++){
    System.out.println(rsmd.getColumnName(i) + ": " + (result.getObject(i)).toString());
    cs.close();
    conn.close();
    Whe I try to get the ResultSet:
    ResultSet result = ((OracleCallableStatement)cs).getCursor(1);
    I receive an error like this:
    java.lang.UnsatisfiedLinkError: make_statement
         at oracle.jdbc.oci8.OCIDBAccess.make_statement(Native Method)
         at oracle.jdbc.oci8.OCIDBAccess.RefCursorBytesToDBStatement(OCIDBAccess.java:2401)
         at oracle.jdbc.driver.OracleStatement.getCursorValue(OracleStatement.java:3865)
         at oracle.jdbc.driver.OracleCallableStatement.getCursor(OracleCallableStatement.java:793)
         at pruebas.Callable.main(Callable.java:44)
    Exception in thread "main"
    In the web I found some examples but using a thin driver. In my case I must use the OCI driver.
    If somebody have any idea about the cause of this problem, please, tell me.
    regards,
    Alvaro

    hi,
    Mine is a standalone class which just calls a stored procedure which returns a REF CURSOR. When i try using getObject() method, i am getting the same error. i understand this is more of a configuration issue rather than a code issue. i have also called some other procedures from my class, which do some updates, etc and which are working fine. The error is as follows:-
    Exception in thread "main" java.lang.UnsatisfiedLinkError: make_statement
    at oracle.jdbc.oci8.OCIDBAccess.make_statement(Native Method)
    at oracle.jdbc.oci8.OCIDBAccess.RefCursorBytesToDBStatement(OCIDBAccess.java:2419)
    at oracle.jdbc.driver.OracleStatement.getCursorValue(OracleStatement.java:3836)
    at oracle.jdbc.driver.OracleStatement.getObjectValue(OracleStatement.java:6039)
    at oracle.jdbc.driver.OracleStatement.getObjectValue(OracleStatement.java:5827)
    at oracle.jdbc.driver.OracleCallableStatement.getObject(OracleCallableStatement.java:698)
    at com.fmr.fims.common.StagingDatabaseHandler.getBatchListForStatus(StagingDatabaseHandler.java:160)
    at com.fmr.fims.common.StagingDatabaseHandler.main(StagingDatabaseHandler.java:39)
    i am unable to get to any solution to this issue. Trying not to use ResulSet wont work because the cursor does have a variable number of records which need to be retrieved one by one.
    Somebody please help. This is urgent.
    My code snippet is :-
    Connection conn = getConnection();
    CallableStatement stmt = conn.prepareCall("{call FEBCHK_ACTIONS.SP_GET_FAILED_BATCH_DOCS(?)}");
    stmt.registerOutParameter(1,oracle.jdbc.OracleTypes.CURSOR);
    boolean exec = stmt.execute();
    if(exec){
    ResultSet rs = (ResultSet)stmt.getObject(1);
    while(rs.next()){.......
    The line
    ResultSet rs = (ResultSet)stmt.getObject(1);
    gives the error.

  • Return ref cursor from database link/stored proc? do-able?

    Is it possible to return a REF CURSOR from a stored procedure that is being called from a remote database via a database link???
    We are trying from Pro*Cobol on MVS (which has db link pointing to AIX thru db link) and get a 00993 error, which seems to say this is not possible.
    Before I give up, thought I would check with the experts....
    Thanks in advance.

    You can't return Java objects as stored procedure or query results.
    Douglas

  • Stored PL/SQL function that returns REF CURSOR type

    Hello everyone,
    I've come through the following problem:
    1.- I created an PL/SQL stored procedure which returns a REF CURSOR element, definition looks like this:
    PACKAGE PKG_LISTADOS AS
    TYPE tuplas IS REF CURSOR;
    /* Procedimientos exportados por el paquete */
    PROCEDURE inicializarModuloListados;
    FUNCTION recaudacionUltimoMes(medioPago DEF_MEDIO_PAGO.MEDIO_PAGO%TYPE)
    RETURN tuplas;
    2.- Now I would like to call the stored procedure and retrieve the PL/SQL cursor as a ResultSet Java Object. The code I wrote is this:
    Connection conn;
    XmlDocument paramDef;
    conn=poolMgr.getConnection str_poolDBConnection);
    try
    CallableStatement cstmt=conn.prepareCall("{?=call PKG_LISTADOS.recaudacionUltimoMes(?)}");
    cstmt.registerOutParameter(1, java.sql.Types.OTHER);
    cstmt.setString(2, "MONEDA");
    cstmt.executeQuery();
    ResultSet rs=(ResultSet)cstmt.getObject(1);
    catch(SQLException sqlE)
    3.- However, I can't make it OK, all the time I get the following error:
    SQL Error(17004), java.sql.SQLException: Non valid column type
    May anyone help me with this, thanks in advance:
    Miguel-Angel

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by angelrip:
    Hello everyone,
    I've come through the following problem:
    1.- I created an PL/SQL stored procedure which returns a REF CURSOR element, definition looks like this:
    PACKAGE PKG_LISTADOS AS
    TYPE tuplas IS REF CURSOR;
    /* Procedimientos exportados por el paquete */
    PROCEDURE inicializarModuloListados;
    FUNCTION recaudacionUltimoMes(medioPago DEF_MEDIO_PAGO.MEDIO_PAGO%TYPE)
    RETURN tuplas;
    2.- Now I would like to call the stored procedure and retrieve the PL/SQL cursor as a ResultSet Java Object. The code I wrote is this:
    Connection conn;
    XmlDocument paramDef;
    conn=poolMgr.getConnection str_poolDBConnection);
    try
    CallableStatement cstmt=conn.prepareCall("{?=call PKG_LISTADOS.recaudacionUltimoMes(?)}");
    cstmt.registerOutParameter(1, java.sql.Types.OTHER);
    cstmt.setString(2, "MONEDA");
    cstmt.executeQuery();
    ResultSet rs=(ResultSet)cstmt.getObject(1);
    catch(SQLException sqlE)
    3.- However, I can't make it OK, all the time I get the following error:
    SQL Error(17004), java.sql.SQLException: Non valid column type
    May anyone help me with this, thanks in advance:
    Miguel-Angel<HR></BLOCKQUOTE>
    Do something like the following:
    cstmt = conn.prepareCall("{call customer_proc(?, ?)}");
    //Set the first parameter
    cstmt.setInt(1, 40);
    //Register to get the Cursor parameter back from the procedure
    cstmt.registerOutParameter(2, OracleTypes.CURSOR);
    cstmt.execute();
    ResultSet cursor = ((OracleCallableStatement)cstmt).getCursor(2);
    while(cursor.next())
    System.out.println("CUSTOMER NAME: " + cursor.getString(1));
    System.out.println("CUSTOMER AGE: " + cursor.getInt(2));
    cursor.close();
    null

  • Q: NULL return REF CURSOR from a PL/SQL function

    I was told that PL/SQL does not handle properly NULL REF CURSORS.
    Here's my implementation in a PL/SQL package
    PACKAGE SPEC:
    TYPE z_rec IS RECORD (
    TYPE z_cur IS REF CUR RETURN z_rec;
    FUNCTION some_function(
    p_msg OUT VARCHAR2)
    RETURN z_cur;
    PACKAGE BODY:
    FUNCTION some_function(
    p_msg OUT VARCHAR2)
    RETURN z_cur
    IS
    retval z_cur;
    OPEN retval FOR
    SELECT ...
    -- Successfull data retrieval
    p_msg := NULL;
    RETURN retval;
    EXCEPTION
    WHEN OTHERS THEN
    p_msg := SUBSTR( SQLERRM, 1, 255 );
    RETURN NULL;
    END some_function;
    I am expecting that a user of this function would call it and test p_msg (output parameter)
    1. IS NULL p_msg it means there were no errors encounetered. The returned cursor can be NULL though (i.e. no records retrieved)
    2. IS NOT NULL p_msg, it means that there were errors and the returned cursor is not usable.
    My question is:
    what are the pitfalls of this approach?
    Thanks a lot.

    user10817976 wrote:
    I asked and still waiting for the answer.
    retval z_cur;
    What I am afraid for is that
    OPEN retval FOR
    SELECT ...
    EXCEPTION
    retval := NULL;
    tries to open the cursor. What happens in case of error? Well, I imagine retval is still NULL. Do I need to (try) to close the cursor in the EXCEPTION section (in order not to misuse the number of cursors in the pool?) That's my worry.No.
    If there is an error opening the cursor the cursor will not be open and will not need closing.
    The code should simply be
    function some_function
        return z_cur
    is
        retval z_cur;
    begin
        open retval for
            select ...
        return retval;
    end some_function;        It is bad practice for a function to have output parameters.
    It is bad practice to turn exceptions into return codes.
    http://tkyte.blogspot.com/2008/06/when-others-then-null-redux.html
    Remember everyone, everyone remember, keep in mind:
    When others not followed by RAISE or RAISE_APPLICATION_ERROR is almost certainly, with 99.999999999% degree of accuracy, a bug in your developed code. Just say "no" to when others not followed by raise or raise_application_error!Read the links, it leads to problems over and over again.

  • Invalid SQL error using REF CURSOR

    I'm getting an "invalid SQL statement" in my function that is returning a REF CURSOR. I have tested this function in SQL*Plus and it works fine.
    -- package level variable
    TYPE t_cursor IS REF CURSOR;
    Function find_patient
         p_ssan IN varchar2,
         p_patient_details OUT t_cursor
         RETURN t_cursor
         IS
         v_cursor t_cursor;
         BEGIN
         OPEN v_cursor FOR
         SELECT name,sex,pay_grade,
              FLOOR(MONTHS_BETWEEN(sysdate,birthdate) / 12) AS age,
              patient_num
         FROM patient
         WHERE ssan = p_ssan;
         p_patient_details := v_cursor;
         RETURN p_patient_details;
         END find_patient;
    -- C# code
    OracleParameter ssan_in = new OracleParameter("p_ssan",OracleDbType.Varchar2);
    OracleParameter cursor_out = new OracleParameter("p_patient_details",OracleDbType.RefCursor);
    cmd.Parameters.Add(ssan_in).Direction = ParameterDirection.Input;
    cmd.Parameters.Add(cursor_out).Direction = ParameterDirection.Output;
    ssan_in.Value = "555555555";
    OracleRefCursor cur = (OracleRefCursor) cursor_out.Value;
    try
    dbconn.Open();
                        OracleDataReader dr = cmd.ExecuteReader();
                        while (dr.Read())
                             pat_name.Text = dr["NAME"].ToString();
                             age.Text = dr["AGE"].ToString();
                             rank.Text = dr["PAY_GRADE"].ToString();
                             gender.Text = dr["SEX"].ToString();
                             pat_num.Text = dr["PATIENT_NUM"].ToString();
    Any suggestions?

    First, you have an output parameter of type ref cursor and a return value. You shouldn't have both.
    Second, try CommandType.Text and a CommandText like:
    "begin :rc := find_patient(:ssan); end;"
    It's easier to see how to bind the parameters like that. Bind first a OracleRefCursor output parameter, then an ssan%type InputParameter.
    David

  • Error wrt Ref Cursor.

    Hi all,
    I have a package, and I am using the ref Cursor in my procedure. Here it is .....
    CREATE OR REPLACE PACKAGE BLABLA_PKG AS
    TYPE OUT_CURSOR IS REF CURSOR;
    PROCEDURE BLABLA_VIEW_PROCEDURE (BUS_ID IN VARCHAR2,
    XML_OUTPUT_CURSOR OUT OUT_CURSOR);
    END BLABLA_PKG;
    CREATE OR REPLACE PACKAGE BODY BLABLA_PKG AS
    PROCEDURE BLABLA_VIEW_PROCEDURE (BUS_ID IN VARCHAR2,
    XML_OUTPUT_CURSOR OUT OUT_CURSOR)
    IS
    V_CURSOR OUT_CURSOR;
    BEGIN
    OPEN V_CURSOR FOR
    SELECT SYS.XMLTYPE.getClobVal(OBJECT_VALUE)
    FROM MBR_VIEW
    WHERE extractValue(OBJECT_VALUE, '/BLABLA_TYPE/BUS/BUS_ID') = 456451232;
    END V_CURSOR;
    END BLABLA_PKG;
    WHEN I try to run the procedure its throwing an error as...
    Error(12,9): PLS-00113: END identifier 'V_CURSOR' must match BLABLA_VIEW_PROCEDURE' at line 2, column 16
    Can anyone help me out from this please??

    Thank you Bakker and sorry for my ignorance.
    And I have modified my packagage and compiled. Now i would like to execute the package. How would i do that?
    CREATE OR REPLACE PACKAGE BLABLA_PKG AS
    PROCEDURE BLABLA_VIEW_PROCEDURE (BLABLA_XML_RS OUT SYS_REFCURSOR, BUS_ID IN VARCHAR2
    END BLABLA_PKG;
    CREATE OR REPLACE PACKAGE BODY BLABLA_PKG AS
    PROCEDURE BLABLA_VIEW_PROCEDURE (BLABLA_XML_RS OUT SYS_REFCURSOR, BUS_ID IN VARCHAR2
    IS
    BEGIN
    OPEN BLABLA_XML_RS FOR
    SELECT SYS.XMLTYPE.getClobVal(OBJECT_VALUE)
    FROM BLABLA_VIEW
    WHERE extractValue(OBJECT_VALUE, '/BLABLA_TYPE/BUS/BUS_ID') = BUS_ID;
    END BLABLA_VIEW_PROCEDURE;
    END BLABLA_PKG;
    I am trying to execute it in the fallowing way, which is not working
    Execute BLABLA_PKG.BLABLA_VIEW_PROCEDURE(1111222, BLABLA_XML_RS);
    Could you please help me out....

  • How to clear the run time error in ref cursor

    good morning every one,
    the code as follows
    create or replace
    procedure Country_sel(key in varchar2)
    as
    cc Res_RelcountryLan.countrycode%type;
    len Res_Language.langname_en%type;
    lid Res_Language.langid%type;
    ab Res_Language.Abrivation%type;
    type refcursorr is ref cursor;
    cur refcursorr;
    d_stmt varchar2(100);
    begin
    d_stmt := 'select RCL.countrycode,RL.langid,RL.langname_'||key||',
    RL.Abrivation from  Res_RelCountryLan RCL inner join Res_Language RL ON RCL.LangId = RL.LangId';
    open cur for d_stmt;
    loop
    fetch cur into cc,lid,len,ab;
    if cur%found then
    dbms_output.put_line(cc||lid||len||ab);
    else
    exit;
    end if;
    end loop;
    close cur;
    commit;
    end  Country_sel;when i am running this code im getting
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    ORA-06512: at "RASOOL.COUNTRY_SEL", line 11
    ORA-06512: at line 6can you please help me in getting rid of this problem.
    thanking you,
    prakash

    d_stmt varchar2(100); Increase the size of d_stmt. Your a assigning a larger string
    d_stmt := 'select RCL.countrycode,RL.langid,RL.langname_'||key||',RL.Abrivation from  Res_RelCountryLan RCL inner join Res_Language RL ON RCL.LangId = RL.LangId'; The size of the above string is more than 100 characters.

  • Error in ref cursor coding

    Error in refcursor
    Edited by: josh1612 on Feb 18, 2010 8:40 PM

    The code of that procedure is
    tId;
    Edited by: josh1612 on Feb 18, 2010 8:41 PM                                                                                                                                                                                           

  • How to handle the ref cursor which is returning "no rows"

    I have written a function which is returning the REF CURSOR. But in one situation the REF CURSOR returns "no rows selected". To handle this situation an exception is raised "when no data found". But i dont know in this situation how should NULL cursor be returned through this function. Since I want to call this function in another procedure so something should be returned through this function by means of ref cursor. But since i am not able to handle this "no rows selected" situation i am not able move further.
    Thanks in advance........

    I agree.
    You would simply process the returned ref cursor irrespective of any rows actually returned in the cursor or not. You would be able to do at least one FETCH from the cursor (even if it does not actually contain any rows) and then determine the %NOTFOUND status to do the rest of the processing.
    SQL> variable cur refcursor
    SQL> exec open :cur for select * from scott.emp where rownum = 1 ;
    PL/SQL procedure successfully completed.
    SQL> print cur
         EMPNO ENAME      JOB              MGR HIREDATE           SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-1980        800                    20
    1 row selected.
    SQL>
    SQL> exec open :cur for select * from scott.emp where 1 = 2 ;
    PL/SQL procedure successfully completed.
    SQL> print cur
    no rows selected
    SQL>
    SQL> SET SERVEROUTPUT ON
    SQL> DECLARE
      2      rec scott.emp%ROWTYPE;
      3      bol BOOLEAN;
      4      cur sys_refcursor;
      5  BEGIN
      6      OPEN cur FOR
      7          SELECT * FROM scott.emp WHERE 1 = 2; /* assume this is your function call returning a ref cursor */
      8      bol := FALSE;
      9      LOOP
    10          FETCH cur
    11              INTO rec;
    12          EXIT WHEN cur%NOTFOUND;
    13          --
    14          -- process the data here
    15          --
    16          bol := TRUE;
    17      END LOOP;
    18      CLOSE cur;
    19      IF (bol)
    20      THEN
    21          dbms_output.put_line('At least one row was found');
    22      ELSE
    23          dbms_output.put_line('No rows were selected');
    24      END IF;
    25  END;
    26  /
    No rows were selected
    PL/SQL procedure successfully completed.
    SQL>

Maybe you are looking for

  • Error while deploying/Undeploying the SOA composite

    Hi All, I am a new bie to OIM 11g. I have created a simple batch file with the commands for deploying/Undeploying/Disbaling/Enabling the SOA composites. I am trying to deploy/Undeploy/Disbale/Enable the SOA composites using the batch file. Following

  • Is there a setting or an app that shows e-mail notifications without having to unlock the screen...like SMS and missed calls?

    Is there a setting or an app for the iPhone 4 that allows you to see that you have new mail messages from the "lock screen" like SMS and missed call messages?  My primary e-mail account is MS Exchange and I'm running iOS 5.  Thanks!

  • Creating PDF from multiple files

    I have dowloaded a 30 trial version of CS4. I make large PDF files from 12 x 12, 300ppi images - anywhere from 20 to 100 files. It all works great in CS2. It's not working at all in CS4. I see the output with choices for web or pdf and have tried usi

  • Sub Dividing BIG Library into Small Ones..Scared to erase.

    I have a single 3tb Library after updating to 10.1 Im trying to now sort into smaller libraries.... Iv created new ones and MOVED Events and Projects into these libraries. ( I TICKED ON ...  Move Proxy and Optimized data.) Its still saying that the o

  • Photoshop CS6 30 day Trial

    I'm trying to download the trial version of Adobe Photoshop but it's not sucessful and don't know why!! I downloaded the Download manager. I've opened it up, signed in with my Adobe ID, selected the program to download (Adobe Photoshop) but then noth