Creating a function having a ref cursor returned

I get an error message for the following code below. I am trying to create a function that allows the users to pass in a certain parameter which is used to invoke a specific query for the paramented passed in. Once the query is invoked, it should return a ref cursor. Please help. I am still using pl/Sql developer.
create or replace package TEST2 is
type rec_DropDownList_Item is RECORD(
TEXT_TYPE VARCHAR2(200),
xsVALUE VARCHAR2(200));
TYPE cur_DropDownList IS REF CURSOR RETURN rec_DropDownList_Item;
FUNCTION Getprocedure_yearreportdisplay (need_type in VARCHAR2) RETURN cur_DropDownList;
end TEST2;
create or replace package body TEST2 is
FUNCTION Getprocedure_yearreportdisplay (need_type in VARCHAR2)
RETURN cur_DropDownList IS
my_ref_cursor cur_DropDownList;
BEGIN
OPEN my_ref_cursor FOR
SELECT vehicletype, vehicledescription
FROM cars where vehicletype = need_type;
return my_ref_cursor;
END Getprocedure_yearreportdisplay;
end TEST2;

user13046875 wrote:
a simple example might help because I am having a difficult understanding the reply. Thank you.
create or replace package TEST2 is
   type rec_DropDownList_Item is RECORD(
   TEXT_TYPE VARCHAR2(200),
   xsVALUE VARCHAR2(200));
   TYPE cur_DropDownList IS REF CURSOR RETURN rec_DropDownList_Item;
   FUNCTION Getprocedure_yearreportdisplay (need_type in VARCHAR2) RETURN cur_DropDownList;
end TEST2;
create or replace package body TEST2 is
FUNCTION Getprocedure_yearreportdisplay (need_type in VARCHAR2)
RETURN cur_DropDownList IS
my_ref_cursor cur_DropDownList;
BEGIN
   OPEN my_ref_cursor FOR
   SELECT 'column1', 'column2'
   FROM dual;
   return my_ref_cursor;
END Getprocedure_yearreportdisplay;
end TEST2;
TUBBY_TUBBZ?variable x refcursor;
TUBBY_TUBBZ?
TUBBY_TUBBZ?exec :x := TEST2.Getprocedure_yearreportdisplay('dummy');
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.01
TUBBY_TUBBZ?print :x
'COLUMN 'COLUMN
column1 column2
1 row selected.
Elapsed: 00:00:00.03
TUBBY_TUBBZ?Is an example of running in SQLPLUS (you may want to get your own copy, it's free and available on OTN).

Similar Messages

  • Importing function with multiple ref cursors in Stored Procedure of Oracle 12c database Using EF6

    Hi Good day!
    I can able to import function for stored procedure of oracle db and able to add the complex type and get the output but i tried to import the procedure which having two ref cursors and unable to retrieve the column information. Only able to retrieve the
    columns of first ref cursor.  Please help me to get the result of two ref cursors which acting as out parameters.

    Having to ref cursors return mutiple recordsets in an Oracle package is like haveng two resultsets return from a MS SQL Server sparc.
    The link may point you in the right direction.
    http://www.codeproject.com/Articles/675933/Returning-Multiple-Result-Sets-from-an-Entity-Fram

  • [Solved] 27.8.4 How to Create a VO on a REF CURSOR - Missing first row

    Searching the forum I found: BC4J - Get one less row from view object.
    Dive into BC4J related  --REF CURSOR (Resultset)
    The first message did not have any answers, and the second had a follow up question - still no answers though - and I thought I would try a different title.
    (This is off topic, but it would be a great help if the search results also displayed the number of replys in the thread. That way, I wouldn't have to view the messages that don't have responses.)
    (This will be deployed on a server that has the ADF for JDeveloper 10.1.2 installed, so using that version of JDeveloper to develop the app.)
    Okay, back to the problem ==>
    I created a VO from a ref cursor, using the manual as a guide. When I run a page that displays a read only table of the view object, I am missing the first row. (Always the first row!) I don't have any order set, and if I call the ref cursor in a Java program for testing, I see all rows and the count is correct.
    One other point, when I call the page, I get the following validation error:
    Validation Error
    You must correct the following error(s) before proceeding:
    * JBO-29000: Unexpected exception caught: java.lang.ClassCastException, msg=null
    * null
    I still see the table, it is just missing the first row of data.
    In my form I have first, previous set, next set , and last
    navigation buttons. If I press last then first, the error goes away. I still don't see the missing row though.
    Any guidance would be appreciated! I can post my code, but it is pretty much the same code in the AdvancedViewObjectExamples.zip in the ViewObjectOnRefCursor example. I just substituted my two package calls (getRefCursor and getRefCursorCount).
    Thanks, Ken

    Went back to a backup copy of the source. Fixed the error. Now I'm back to just not being able to see the first row of data.
    Additional Note: I had removed fields in the display. Once I truncated the ps_txn table in the schema defined by the model, the data would display (Still without the first record.)
    Are there any examples that are more in depth than the few pages in the developer guide?
    Here is the code for my VOImpl class:
    package newslinearchive.model.datamodel;
    import java.math.BigDecimal;
    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.sql.Types;
    import oracle.jbo.InvalidParamException;
    import oracle.jbo.JboException;
    import oracle.jbo.domain.Date;
    import oracle.jbo.domain.Number;
    import oracle.jbo.server.DBTransaction;
    import oracle.jbo.server.QueryCollection;
    import oracle.jbo.server.SQLBuilder;
    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;
    // --- File generated by Oracle ADF Business Components Design Time.
    // --- Custom code may be added to this class.
    // --- Warning: Do not modify method signatures of generated methods.
    public class SearchRefCursorImpl extends ViewObjectImpl {
    * This is the default constructor (do not remove)
    public SearchRefCursorImpl() {
    * Overridden framework method.
    * Executed when the framework needs to issue the database query for
    * the query collection based on this view object. One view object
    * can produce many related result sets, each potentially the result
    * of different bind variable values. If the rowset in query is involved
    * in a framework-coordinated master/detail viewlink, then the params array
    * will contain one or more framework-supplied bind parameters. If there
    * are any user-supplied bind parameter values, they will PRECEED the
    * framework-supplied bind variable values in the params array, and the
    * number of user parameters will be indicated by the value of the
    * numUserParams argument.
    protected void executeQueryForCollection(Object qc,Object[] params,int numUserParams) {
    storeNewResultSet(qc,retrieveRefCursor(qc,params));
    super.executeQueryForCollection(qc, params, numUserParams);
    * Overridden framework method.
    * Wipe out all traces of a built-in query for this VO
    protected void create() {
    getViewDef().setQuery(null);
    getViewDef().setSelectClause(null);
    setQuery(null);
    * Overridden framework method.
    * The role of this method is to "fetch", populate, and return a single row
    * from the datasource by calling createNewRowForCollection() and populating
    * its attributes using populateAttributeForRow().
    protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {
    * We ignore the JDBC ResultSet passed by the framework (null anyway) and
    * use the resultset that we've stored in the query-collection-private
    * user data storage
    rs = getResultSet(qc);
    * Create a new row to populate
    ViewRowImpl r = createNewRowForCollection(qc);
    try {
    * Populate new row by attribute slot number for current row in Result Set
    // populateAttributeForRow(r,0, rs.getLong(1));
    // populateAttributeForRow(r,1, rs.getString(2));
    // populateAttributeForRow(r,2, rs.getString(3));
    // MASTERID NOT NULL NUMBER
    populateAttributeForRow(r,0, rs.getBigDecimal(1));
    //ID NOT NULL NUMBER
    populateAttributeForRow(r,1, rs.getBigDecimal(2));
    // CAID NOT NULL NUMBER
    populateAttributeForRow(r,2, rs.getBigDecimal(3));
    // LANGUAGE NOT NULL VARCHAR2(30)
    populateAttributeForRow(r,3, rs.getString(4));
    // IS_CURRENT_VERSION NOT NULL NUMBER(1)
    populateAttributeForRow(r,4, rs.getBigDecimal(5));
    // FOLDER_ID NOT NULL NUMBER
    populateAttributeForRow(r,5, rs.getBigDecimal(6));
    // FOLDER_REGION_ID NOT NULL NUMBER
    populateAttributeForRow(r,6, rs.getBigDecimal(7));
    // NAME NOT NULL VARCHAR2(256)
    populateAttributeForRow(r,7, rs.getString(8));
    // DISPLAY_NAME VARCHAR2(256)
    populateAttributeForRow(r,8, rs.getString(9));
    // ITEMTYPE NOT NULL VARCHAR2(30)
    populateAttributeForRow(r,9, rs.getString(10));
    // SUBTYPE VARCHAR2(40)
    populateAttributeForRow(r,10, rs.getString(11));
    // SUBTYPE_CAID NUMBER
    populateAttributeForRow(r,11, rs.getBigDecimal(12));
    // PARENT_ITEM_ID NUMBER
    populateAttributeForRow(r,12, rs.getBigDecimal(13));
    // CATEGORY_ID NUMBER
    populateAttributeForRow(r,13, rs.getBigDecimal(14));
    // CATEGORY_CAID NUMBER
    populateAttributeForRow(r,14, rs.getBigDecimal(15));
    // AUTHOR VARCHAR2(50)
    populateAttributeForRow(r,15, rs.getString(16));
    // DESCRIPTION VARCHAR2(2000)
    populateAttributeForRow(r,16, rs.getString(17));
    // PUBLISH_DATE NOT NULL DATE
    populateAttributeForRow(r,17, rs.getDate(18));
    // EXPIREMODE VARCHAR2(90)
    populateAttributeForRow(r,18, rs.getString(19));
    // EXPIRENUMBER NUMBER
    populateAttributeForRow(r,19, rs.getBigDecimal(20));
    // EXPIREDATE DATE
    populateAttributeForRow(r,20, rs.getDate(21));
    // IMAGE VARCHAR2(350)
    populateAttributeForRow(r,21, rs.getString(22));
    // KEYWORDS VARCHAR2(2000)
    populateAttributeForRow(r,22, rs.getString(23));
    // URL VARCHAR2(4000)
    populateAttributeForRow(r,23, rs.getString(24));
    // FILENAME VARCHAR2(350)
    populateAttributeForRow(r,24, rs.getString(25));
    // TEXT CLOB()
    populateAttributeForRow(r,25, rs.getClob(26));
    // FOLDER_LINK_ID NUMBER
    populateAttributeForRow(r,26, rs.getBigDecimal(27));
    // FOLDER_LINK_CAID NUMBER
    populateAttributeForRow(r,27, rs.getBigDecimal(28));
    // ACTIVE NOT NULL NUMBER(1)
    populateAttributeForRow(r,28, rs.getBigDecimal(29));
    // CAN_BE_CHECKEDOUT NUMBER(1)
    populateAttributeForRow(r,29, rs.getBigDecimal(30));
    // IS_ITEM_CHECKEDOUT NUMBER(1)
    populateAttributeForRow(r,30, rs.getBigDecimal(31));
    // CHECKER_USERNAME VARCHAR2(256)
    populateAttributeForRow(r,31, rs.getString(32));
    // CHECKOUT_DATE DATE
    populateAttributeForRow(r,32, rs.getDate(33));
    // FULLSCREEN NOT NULL NUMBER(1)
    populateAttributeForRow(r,33, rs.getBigDecimal(34));
    // INPLACE NOT NULL NUMBER(1)
    populateAttributeForRow(r,34, rs.getBigDecimal(35));
    // CREATEDATE NOT NULL DATE
    populateAttributeForRow(r,35, rs.getDate(36));
    // CREATOR NOT NULL VARCHAR2(256)
    populateAttributeForRow(r,36, rs.getString(37));
    // UPDATEDATE DATE
    populateAttributeForRow(r,37, rs.getDate(38));
    // UPDATOR VARCHAR2(256)
    populateAttributeForRow(r,38, rs.getString(39));
    // SECURITY VARCHAR2(25)
    populateAttributeForRow(r,39, rs.getString(40));
    // VISIBLE NOT NULL NUMBER(1)
    populateAttributeForRow(r,40, rs.getBigDecimal(41));
    // SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,41, rs.getBigDecimal(42));
    // CATEGORY_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,42, rs.getBigDecimal(43));
    // AUTHOR_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,43, rs.getBigDecimal(44));
    // CREATE_DATE_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,44, rs.getBigDecimal(45));
    // ITEMTYPE_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,45, rs.getBigDecimal(46));
    catch (SQLException s) {
    throw new JboException(s);
    return r;
    * Overridden framework method.
    * Return true if the datasource has at least one more record to fetch.
    protected boolean hasNextForCollection(Object qc) {
    ResultSet rs = getResultSet(qc);
    boolean nextOne = false;
    try {
    nextOne = rs.next();
    * When were at the end of the result set, mark the query collection
    * as "FetchComplete".
    if (!nextOne) {
    setFetchCompleteForCollection(qc, true);
    * Close the result set, we're done with it
    rs.close();
    catch (SQLException s) {
    throw new JboException(s);
    return nextOne;
    * Overridden framework method.
    * The framework gives us a chance to clean up any resources related
    * to the datasource when a query collection is done being used.
    protected void releaseUserDataForCollection(Object qc, Object rs) {
    * Ignore the ResultSet passed in since we've created our own.
    * Fetch the ResultSet from the User-Data context instead
    ResultSet userDataRS = getResultSet(qc);
    if (userDataRS != null) {
    try {
    userDataRS.close();
    catch (SQLException s) {
    /* Ignore */
    super.releaseUserDataForCollection(qc, rs);
    * Overridden framework method
    * Return the number of rows that would be returned by executing
    * the query implied by the datasource. This gives the developer a
    * chance to perform a fast count of the rows that would be retrieved
    * if all rows were fetched from the database. In the default implementation
    * the framework will perform a SELECT COUNT(*) FROM (...) wrapper query
    * to let the database return the count. This count might only be an estimate
    * depending on how resource-intensive it would be to actually count the rows.
    public long getQueryHitCount(ViewRowSetImpl viewRowSet) {
    Long result = (Long)callStoredFunction(NUMBER,
    "PORTAL.SEARCH_REFCURSOR.getRefCursorCount",
    viewRowSet.getParameters(true));
    return result.longValue();
    // ------------- PRIVATE METHODS ----------------
    * Return a JDBC ResultSet representing the REF CURSOR return
    * value from our stored package function.
    * new Object[]{getNamedBindParamValue("Email",params)}
    private ResultSet retrieveRefCursor(Object qc, Object[] params) {
    ResultSet rs = (ResultSet)callStoredFunction(OracleTypes.CURSOR,
    "PORTAL.SEARCH_REFCURSOR.getRefCursor",
    null);
    return rs ;
    private Object getNamedBindParamValue(String varName, Object[] params) {
    Object result = null;
    if (getBindingStyle() == SQLBuilder.BINDING_STYLE_ORACLE_NAME) {
    if (params != null) {
    for (Object param : params) {
    Object[] nameValue = (Object[])param;
    String name = (String)nameValue[0];
    if (name.equals(varName)) {
    return (String)nameValue[1];
    throw new JboException("No bind variable named '"+varName+"'");
    * Store a new result set in the query-collection-private user-data context
    private void storeNewResultSet(Object qc, ResultSet rs) {
    ResultSet existingRs = getResultSet(qc);
    // If this query collection is getting reused, close out any previous rowset
    if (existingRs != null) {
    try {existingRs.close();} catch (SQLException s) {}
    setUserDataForCollection(qc,rs);
    hasNextForCollection(qc); // Prime the pump with the first row.
    * Retrieve the result set wrapper from the query-collection user-data
    private ResultSet getResultSet(Object qc) {
    return (ResultSet)getUserDataForCollection(qc);
    * Return either null or a new oracle.jbo.domain.Date
    private static Date nullOrNewDate(Timestamp t) {
    return t != null ? new Date(t) : null;
    * Return either null or a new oracle.jbo.domain.Number
    private static Number nullOrNewNumber(BigDecimal b) {
    try {
    return b != null ? new Number(b) : null;
    catch (SQLException s) { }
    return null;
    //----------------[ Begin Helper Code ]------------------------------
    public static int NUMBER = Types.NUMERIC;
    public static int DATE = Types.DATE;
    public static int VARCHAR2 = Types.VARCHAR;
    public static int CLOB = Types.CLOB;
    * Simplifies calling a stored function with bind variables
    * You can use the NUMBER, DATE, and VARCHAR2 constants in this
    * class to indicate the function return type for these three common types,
    * otherwise use one of the JDBC types in the java.sql.Types class.
    * NOTE: If you want to invoke a stored procedure without any bind variables
    * ==== then you can just use the basic getDBTransaction().executeCommand()
    * @param sqlReturnType JDBC datatype constant of function return value
    * @param stmt stored function statement
    * @param bindVars Object array of parameters
    * @return function return value as an Object
    protected Object callStoredFunction(int sqlReturnType, String stmt,
    Object[] bindVars) {
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement("begin ? := " + stmt +
    "; end;", 0);
    st.registerOutParameter(1, sqlReturnType);
    if (bindVars != null) {
    for (int z = 0; z < bindVars.length; z++) {
    st.setObject(z + 2, bindVars[z]);
    st.executeUpdate();
    return st.getObject(1);
    catch (SQLException e) {
    throw new JboException(e);
    finally {
    if (st != null) {
    try {
    st.close();
    catch (SQLException e) {}
    /**Gets the bind variable value for Email
    public String getEmail() {
    return (String)getNamedWhereClauseParam("Email");
    /**Sets <code>value</code> for bind variable Email
    public void setEmail(String value) {
    setNamedWhereClauseParam("Email", value);
    /**getEstimatedRowCount - overridden for custom java data source support.
    public long getEstimatedRowCount() {
    long value = super.getEstimatedRowCount();
    return value;
    Thanks, Ken

  • How to read my cursor that is ref cursor returning user defined type

    Hi
    I have types defined as follows:
    TYPE MY_RECORD IS RECORD (
    COL1 TABLE1.COL1%TYPE,
    COL2 TABLE1.COL2%TYPE
    TYPE MY_CURSOR IS REF CURSOR
    RETURN MY_RECORD;This is used as return type in a stored procedure.
    I have a pl/sql block where I make a call to the SP that returns this cursor.
    How can I read individual values being returned from SP?

    SQL> create or replace package pkg
    as
       type my_record is record (col1 emp.empno%type, col2 emp.ename%type);
       type my_cursor is ref cursor
          return my_record;
       procedure p (cur out my_cursor);
    end pkg;
    Package created.
    SQL> create or replace package body pkg
    as
       procedure p (cur out my_cursor)
       as
       begin
          open cur for
             select   empno, ename
               from   emp
              where   rownum <= 2;
       end p;
    end pkg;
    Package body created.
    SQL> declare
       cur     pkg.my_cursor;
       e_rec   pkg.my_record;
    begin
       pkg.p (cur);
       loop
          fetch cur into   e_rec;
          exit when cur%notfound;
          dbms_output.put ('Empno: ' || e_rec.col1);
          dbms_output.put_line ('; Ename: ' || e_rec.col2);
       end loop;
       close cur;
    end;
    Empno: 7369; Ename: SMITH
    Empno: 7499; Ename: ALLEN
    PL/SQL procedure successfully completed.

  • Ref cursor returns login ids

    I have this ref cursor that returns login ids from a procedure.
    While I can define the ref cursor as sys_refcursor; I want to use strongly typed ref cursor ( for improved readabilty of code).
    But I guess I can not define the cursor that returns %type.
    e.g. Type return_login_id IS REF CURSOR return tab1.login_id%type;
    On compilation the package threw an error saying the return type should be record.
    I need to define a record with one column and use that as return type ?
    any other way around ?
    TIA
    S

    Btw, why you need to use REF Cursor?
    You can use just a cursor:
    SQL> declare
      2  cursor c1 is select empid from emp;
      3  TYPE my_id IS TABLE OF emp.empid%type;
      4  myid my_id := my_id();
      5  BEGIN
      6  OPEN c1;
      7  FETCH c1 BULK COLLECT INTO myid;
      8  CLOSE c1;
      9  END;
    10  /
    PL/SQL procedure successfully completed.
    SQL>

  • Ref cursor return type

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

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

  • Pro*C program to use a REF CURSOR returned by a DB Function

    Hi,
    Please help me with this.
    I have a pro*c program that should call a
    database function which returns a ref cursor.
    This is the sample code i have :-
    EXEC SQL BEGIN DECLARE SECTION;
    SQL_CURSOR emptycabin_cursor;
    int cabinid;
    EXEC SQL END DECLARE SECTION;
    EXEC SQL ALLOCATE :emptycabin_cursor;
    EXEC SQL EXECUTE BEGIN
    :emptycabin_cursor:=posremptycabin(:voy,:segid);
    END;END-EXEC;
    /* more_records = 1*/
    while (more_records)
    EXEC SQL FETCH :emptycabin_cursor INTO :cabinid;
    if (SQLCODE==NOTFOUND)
    {more_records=FALSE;break;}
    EXEC SQL close :emptycabin_cursor;
    When I execute I keep getting fetch out of sequence error.
    Can someone let me know whats wrong with this code?
    When I execute the function from sqlplus
    variable ref_cur refcursor ;
    exec :ref_cur:=posremptycabin(232,'CC');
    print :ref_cur;
    I get the data properly displayed.So nothing wrong with the function.
    Thanks for your help

    I know nothing about Pro*C, but Tom Kyte's Pro*C example for ref cursors fetches the cursor with a loop that looks like:
    for( ;; )
            EXEC SQL WHENEVER NOTFOUND DO break;
            EXEC SQL FETCH :my_cursor INTO :ename, empno;
            printf( "'%.*s', %d\n", ename.len, ename.arr, empno );
        EXEC SQL CLOSE :my_cursor;http://asktom.oracle.com/~tkyte/ResultSets/index.html
    Hope this helps.

  • How to call a function having OBJECT type as Return type

    Hi,
    I've the following function returning OBJECT type.
    Pease advice me how to call this function
    CREATE OR REPLACE TYPE GET_EMP_OBJ is object
       ( emp_name varchar2(50) ,
         mgr_id   number,
         dept_id  number
    CREATE OR REPLACE FUNCTION get_emp(P_emp_no NUMBER )
      RETURN GET_EMP_OBJ  IS
      t_emp_info GET_EMP_OBJ ;
      v_ename  EMP.ename%TYPE;
      v_mgr    EMP.mgr%TYPE ;
      v_deptno EMP.deptno%TYPE;
      v_ename1  EMP.ename%TYPE;
      v_mgr1    EMP.mgr%TYPE ;
      v_deptno1 EMP.deptno%TYPE;
    BEGIN
      FOR rec IN ( SELECT ename , mgr , deptno
                     FROM emp )
      LOOP
         v_ename := rec.ename ;
         v_ename1 := v_ename1||'|'||v_ename ;
         v_mgr   := rec.mgr   ;
         v_mgr1  := v_mgr1||'|'||v_mgr ;
         v_deptno:= rec.deptno;
         v_deptno1 := v_deptno1||'|'||v_deptno ;
      END LOOP ;
      t_emp_info  := GET_EMP_OBJ (v_ename,v_mgr,v_deptno ) ;
      RETURN t_emp_info ;
    EXCEPTION WHEN OTHERS THEN
      DBMS_OUTPUT.put_line ('Error'||SQLCODE||','||SQLERRM ) ;
    END;The above function got created successfully.
    And i'm confused how to call this functions. I tried like below but didn't work
    DECLARE
      t_emp_info_1  GET_EMP_OBJ ;
    BEGIN
       t_emp_info_1 := get_emp(7566) ;
       for i in 1..t_emp_info_1.COUNT
          LOOP
             DBMS_OUTPUT.put_line ('Values are'||i.emp_name ) ;
         END LOOP;
    END;  

    SQL> CREATE OR REPLACE TYPE GET_EMP_OBJ is object
      2     ( emp_name varchar2(50) ,
      3       mgr_id   number,
      4       dept_id  number
      5     );
      6  /
    Type created.
    SQL> ed
    Wrote file afiedt.buf
      1  CREATE OR REPLACE FUNCTION get_emp(empno NUMBER )
      2    RETURN GET_EMP_OBJ  IS
      3    t_emp_info GET_EMP_OBJ ;
      4  BEGIN
      5    begin
      6      select get_emp_obj(ename, mgr, deptno) into t_emp_info
      7      from emp
      8      where empno = get_emp.empno;
      9    exception
    10      when no_data_found then
    11        t_emp_info := new get_emp_obj(null,null,null);
    12    end;
    13    return t_emp_info;
    14* END;
    SQL> /
    Function created.
    SQL> set serverout on
    SQL>
    SQL> declare
      2    t_emp_info  GET_EMP_OBJ ;
      3  BEGIN
      4     t_emp_info := get_emp(7566);
      5     DBMS_OUTPUT.put_line ('Values are: '||t_emp_info.emp_name||', '||t_emp_info.mgr_id||', '||t_emp_info.dept_id);
      6  END;
      7  /
    Values are: JONES, 7839, 20
    PL/SQL procedure successfully completed.
    SQL>

  • How to create a procedure to output REF CURSOR with any WHERE clause?

    I have an requirement like this: I have huge query which need to reuse in my code more than 10 times. This SQL has about 50 lines. Thing is for those 10 odd times sometimes the WHERE clause changes (columns are the same). So I cannot create a view since SQL is not static.
    I thought of writing a procedure with a WHERE_CLAUSE input para. I output a sys refcursor by adding the where clause. But I can't do it since you cannot add a where clause like that.
    i.e.
    PROCEDURE dynamyic_query (p_where_clause IN VARCHAR2, p_out_query OUT SYS_REFCURSOR ) IS
    BEGIN
      OPEN p_out_query FOR SELECT ......... FROM table WHERE || ' ' || p_where_clause;
    END;The above gives error.
    How to handle a situation like this???? Any help would be greatly appreciated.

    I tried this method:
    I created a table tab_test which has these records:
    TNAME                          TABTYPE    CLUSTERID                                                                                                                                                                  
    ABS_V4_P_ERROR_MESSAGES        TABLE                                                                                                                                                                                  
    ABS_V4_P_ORG_PARAM             TABLE                                                                                                                                                                                  
    ABS_V4_P_PARAMETER             TABLE                                                                                                                                                                                  
    ABS_V4_P_SYS_PARAM             TABLE                                                                                                                                                                                  
    ACCINTERFACE_PARAMETERS        TABLE                                                                                                                                                                                  
    ACCOUNTS                       TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS        TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS#       TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS_1      TABLE                                                                                                                                                                                   Now I create this proc:
    PROCEDURE FORMS_TEXT_DYN_SQL_TEST(p_where_cluase IN VARCHAR2, p_out_cursor OUT SYS_REFCURSOR) IS
      v_stmt VARCHAR2(1000);
    BEGIN
      v_stmt := 'SELECT tname FROM tab_test WHERE tname LIKE ''%ABS_V4%'' AND tabtype = :x';
      OPEN p_out_cursor FOR v_stmt using p_where_cluase;
    END;I create this code block and run it:
    declare
      v_tname varchar2(200);
      out_cursor sys_refcursor;
    begin
      forms_text_dyn_sql_test('TABLE', out_cursor );
      LOOP
        fetch out_cursor INTO v_tname;
        exit when out_cursor%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(v_tname);
      END LOOP;
    end;
    /I get correct output:
    ABS_V4_P_ERROR_MESSAGES
    ABS_V4_P_ORG_PARAM
    ABS_V4_P_PARAMETER
    ABS_V4_P_SYS_PARAMHowever, when I change the proc like this:
    PROCEDURE FORMS_TEXT_DYN_SQL_TEST(p_where_cluase IN VARCHAR2, p_out_cursor OUT SYS_REFCURSOR) IS
      v_stmt VARCHAR2(1000);
    BEGIN
      v_stmt := 'SELECT tname FROM tab_test WHERE tname LIKE ''%ABS_V4%'' AND :y';
      OPEN p_out_cursor FOR v_stmt using p_where_cluase;
    END;And run this code block:
    declare
      v_tname varchar2(200);
      out_cursor sys_refcursor;
    begin
      forms_text_dyn_sql_test(' 1 = 1 ', out_cursor );
      LOOP
        fetch out_cursor INTO v_tname;
        exit when out_cursor%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(v_tname);
      END LOOP;
    end;
    /I get error:
    [1]: (Error): ORA-00920: invalid relational operator ORA-06512: at "ABS.FORMS_TEXT_DYN_SQL_TEST", line 6 ORA-06512: at line 5Looks like you can only put column_name = :z, column_name = :y type values. You cannot it seems replace it with any WHERE CLAUSE????

  • REF CURSOR RETURNED FROM STORED PROCEDURE OPENED WITH CURRENT_USER PRIVILEGES

    Hi.
    I was wondering if anyone knows when this bug will be fixed. The bug# is 899567 off of metalink.
    I am running into this problem as well, and we do not want to use OCI/SQLNet as the fix. We have an application with secure data concerns and only want to give access to stored procedures to an application user.
    Thanks,
    Brad

    I'm using version 8.1.6.0.0 on a W2K server.
    PS: a strange behaveour
    if i try to insert a row using the following anonymous pl/sql block
    begin
    insert into objects select 2, 'B', ref(c) from meta.classes c where id =1;
    end;
    i get the following error msg
    ERROR at line 1:
    ORA-06552: PL/SQL: Compilation unit analysis terminated
    ORA-06553: PLS-302: component 'OBJ_T' must be declared
    but if i use only the sql command from the sql plus prompt
    insert into objects select 2, 'B', ref(c) from meta.classes c where id =1;
    the row is inserted.
    OBJ_T is the object type(id number, label varchar2, class ref class_t),
    OBJECTS is a table of obj_t,
    CLASS_T is an object type(id number, label varchar2)
    CLASSES is a table of CLASS_T.
    null

  • 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>

  • Data Set with multiple ref cursors

    Hi ,
    I need to design an integrated report , i created my data set with a oracle procedure which returns "multiple ref cursors" . In this case birt is displaying all output columns together and it is difficult to identify which column belongs to which ref cursor and if there are any columns with same name in both output cursors , it displays only one. Is there any way to handle this ? or how we handle a data set which contains multiple ref cursors in output ??

    Having to ref cursors return mutiple recordsets in an Oracle package is like haveng two resultsets return from a MS SQL Server sparc.
    The link may point you in the right direction.
    http://www.codeproject.com/Articles/675933/Returning-Multiple-Result-Sets-from-an-Entity-Fram

  • 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

  • How to return a table to ref cursor?

    My client has created a package stored procedure that takes in 2 parameters of VarChar2 and an out parameter which is a table
    Following is the package header
    CREATE OR REPLACE PACKAGE "PKG_TRAVEL_NEW_SUND" IS
    ---RECORD TYPE DELARATION
    TYPE DIRECT_ALT_REC IS RECORD (SERVICE_NO CBG_DISTANCE_FARE.SERVICE_NO%TYPE,
    DISTANCE CBG_DISTANCE_FARE.DISTANCE%TYPE,
    CASH_FARE_AC CBG_DISTANCE_FARE.CASH_FARE_AC%TYPE,
    CASH_FARE_NON_AC CBG_DISTANCE_FARE.CASH_FARE_NON_AC%TYPE,
    CARD_FARE_AC CBG_DISTANCE_FARE.CARD_FARE_AC%TYPE,
    CARD_FARE_NON_AC CBG_DISTANCE_FARE.CARD_FARE_NON_AC%TYPE,
    EZLINK_FARE_AC CBG_DISTANCE_FARE.EZLINK_FARE_AC%TYPE,
    EZLINK_FARE_NON_AC CBG_DISTANCE_FARE.EZLINK_FARE_NON_AC%TYPE,
    AVG_RUNTIME CBG_DISTANCE_FARE.AVG_RUNTIME%TYPE,
    ALTERNATIVE_NO CBG_DIRECT_ALT.ALTERNATIVE_NO%TYPE,
    MAX_FREQ_AM CBG_SVC.MAX_FREQ_AM%TYPE,
    MIN_FREQ_AM CBG_SVC.MIN_FREQ_AM%TYPE,
    ADVANTAGE_CODE CBG_DIRECT_ALT.ADVANTAGE_CODE%TYPE,
    DIST_FARE_CODE_1 CBG_DISTANCE_FARE.DIST_FARE_CODE%TYPE,
    DIST_FARE_CODE_2 CBG_DISTANCE_FARE.DIST_FARE_CODE%TYPE,
    DIST_FARE_CODE_3 CBG_DISTANCE_FARE.DIST_FARE_CODE%TYPE,
    FROM_STOP_CODE CBG_DISTANCE_FARE.FROM_STOP_CODE%TYPE,
    TO_STOP_CODE CBG_DISTANCE_FARE.TO_STOP_CODE%TYPE,
    MIN_TIME CBG_DIRECT_ALT.MIN_TIME%TYPE,
    MIN_FARE CBG_DIRECT_ALT.MIN_FARE%TYPE,
                                            ACT_FARE CBG_DIRECT_ALT.MIN_FARE%TYPE,
    TRAVEL_TYPE VARCHAR2(4),
    TRANSFER_INFO VARCHAR2(1),
    END_TRANSFER_INFO VARCHAR2(1));
    --TABLE  TYPE DECLARATION
    TYPE BUS_INFO_TAB IS TABLE OF DIRECT_ALT_REC INDEX BY BINARY_INTEGER;
    -- CURSOR TYPE DECLARATION
    TYPE TEMP_REC_STRUCT1 IS RECORD (
    RECORD_POSITION BINARY_INTEGER,
    DIST_FARE_CODE1 CBG_DISTANCE_FARE.DIST_FARE_CODE%TYPE,
    DIST_FARE_CODE2 CBG_DISTANCE_FARE.DIST_FARE_CODE%TYPE,
    DIST_FARE_CODE3 CBG_DISTANCE_FARE.DIST_FARE_CODE%TYPE,
    ADVANTAGE_CODE CBG_DIRECT_ALT.ADVANTAGE_CODE%TYPE,
    MINIMUM_FARE CBG_DIRECT_ALT.MIN_FARE%TYPE,
    MINIMUM_TIME CBG_DIRECT_ALT.MIN_TIME%TYPE,
    TRAVEL_TYPE VARCHAR2(4) );
    TYPE TEMP_TAB_STRUCT1 IS TABLE OF TEMP_REC_STRUCT1 INDEX BY BINARY_INTEGER;
    TEMP_TABLE1 BUS_INFO_TAB;
    G_RESULTSET_INDEX BINARY_INTEGER := 0 ;
    G_TOT_RECS_IN_TAB1 BINARY_INTEGER := 0 ;
    TYPE BUS_INFO_CUR IS REF CURSOR RETURN DIRECT_ALT_REC;
    ---PROCEDURE INSIDE THE PACKAGE
    --- PROCEDURE TO SELECT THE RECORDS
    PROCEDURE SEL_DIRECT_ALT(P_FROM_STOP_CODE IN VARCHAR2,
    P_TO_STOP_CODE IN VARCHAR2,
    RESULTSET IN OUT BUS_INFO_TAB);
    I'm using ODP.net and here is my code
    string storedprocedure = "PKG_TRAVEL_NEW_SUND.SEL_DIRECT_ALT";
    //PKG_TRAVEL_NEW_SUND
    //CBG003_XP_SP_TEST1
    ArrayList retlist = new ArrayList();
    OracleConnection curr_conn = this.GetOpenConnection();
    OracleCommand cmd = curr_conn.CreateCommand();
    cmd = new OracleCommand(storedprocedure, curr_conn);
    cmd.CommandType = CommandType.StoredProcedure;
    // input parameter
    OracleParameter param1 = new OracleParameter();
    OracleParameter param2 = new OracleParameter();
    param1.ParameterName = "start_code";
    param2.ParameterName = "end_code";
    param1.OracleDbType = OracleDbType.Varchar2;
    param2.OracleDbType = OracleDbType.Varchar2;
    param1.Direction = ParameterDirection.Input;
    param2.Direction = ParameterDirection.Input;
    param1.Size = 5;
    param2.Size = 5;
    param1.Value = start_codes;
    param2.Value = end_codes;     
    cmd.Parameters.Add(param1);
    cmd.Parameters.Add(param2);
    OracleParameter outputparam3 = new OracleParameter();
    outputparam3.Direction = ParameterDirection.InputOutput;
    outputparam3.ParameterName = "output";
    outputparam3.OracleDbType = OracleDbType.RefCursor;
    // output type
    cmd.Parameters.Add(outputparam3);
    cmd.ExecuteNonQuery();
    At this point, when i execute Query, i get the message telling me that i could have the wrong number or type arguments for the procedure.
    I've looked thru countless examples saying i should use a RefCursor, but what else could i miss out?

    Hi,
    This is from Metalink NOTE.219191.1 How to return the values in a PL/SQL table to a ref cursor
    Hope it helps,
    Greg
    This document gives details with an example on how to pass the values
    in a PL/SQL table to a ref cursor.
    SCOPE & APPLICATION
    This document is useful for developers who are familiar with SQL & PL/SQL
    How to return the values in a PL/SQL table to a ref cursor
    This can be done by using a SQL Object type instead of a PL/SQL table.
    Here is an example.
    SQL> create or replace type ObjectType as object
    2 ( x int,
    3 y date,
    4 z varchar2(25)
    5 );
    6 /
    Type created.
    SQL> create or replace type TabType as table of ObjectType;
    2 /
    Type created.
    SQL> create or replace
    2 function demo_function( p_start_row in number,
    3 p_end_row in number )
    4 return TabType
    5 as
    6 l_data TabType := TabType();
    7 l_cnt number default 0;
    8 begin
    9 for x in ( select * from emp order by sal desc )
    10 loop
    11 l_cnt := l_cnt + 1;
    12 if ( l_cnt >= p_start_row )
    13 then
    14 l_data.extend;
    15 l_data(l_data.count) :=
    16 objectType( x.empno,
    17 x.hiredate,
    18 x.ename );
    19 end if;
    20 exit when l_cnt = p_end_row;
    21 end loop;
    22
    23 return l_data;
    24 end;
    25 /
    Function created.
    SQL> select *
    2 from the ( select cast( demo_function(3,7) as TabType )
    3 from dual ) a;
    X Y Z
    7902 03-DEC-81 FORD
    7566 02-APR-81 JONES
    7698 01-MAY-81 BLAKE
    7782 09-JUN-81 CLARK
    7844 08-SEP-81 TURNER
    By using a SQL object type, the table can be selected easily.
    SQL> create or replace package demo_pkg
    2 as
    3 type rc is ref cursor;
    4
    5 procedure p( p_cursor in out rc );
    6 end;
    7 /
    Package created.
    SQL> create or replace package body demo_pkg
    2 as
    3
    4 procedure p( P_cursor in out rc )
    5 is
    6 l_data TabType := TabType();
    7 begin
    8 for i in 1 .. 3 loop
    9 l_data.extend;
    10 l_data(i) :=
    11 ObjectType( i, sysdate+i, i || ' data');
    12 end loop;
    13
    14 open p_cursor for
    15 select *
    16 from TABLE ( cast ( l_data as TabType) );
    17 end;
    18
    19 end;
    20 /
    Package body created.
    SQL> set autoprint on
    SQL> variable x refcursor
    SQL> exec demo_pkg.p(:x)
    PL/SQL procedure successfully completed.
    X Y Z
    1 15-NOV-02 1 data
    2 16-NOV-02 2 data
    3 17-NOV-02 3 data

  • Return csv string as strongly typed ref cursor

    I have a column in a table that is csv delimited and I want to return it (and others) as a strongly typed ref cursor.
    eg
    create table test_tab (mydata varchar2(100))
    insert into test_tab(mydata) values ('"a1","b1","c1","d1"')
    insert into test_tab(mydata) values ('"a2","b2","c2","d2"')
    so test_tab has 1 column and 2 rows:
    "a1","b1","c1","d1"
    "a2","b2","c2","d2"
    So a,b,c,d represent columns in my strongly typed ref cursor
    If I then try something like:
    declare
    type my_rec is record(
    a varchar2(50),
    b varchar2(50),
    c varchar2(50),
    d varchar2(50)
    type my_rec_refc IS REF CURSOR RETURN my_rec;
    my_test_refc my_rec_refc;
    begin
    open my_test_refc for select mydata,mydata,mydata,mydata from test_tab;
    end;
    then it obviously works as my ref cursor is expecting 4 columns. However, what I want to do is break each individual element out of the mydata column. I've played around a bit with dynamic sql but only getting so far and apparently that can't be used with a ref cursor anyway. I need to return a strongly typed cursor as another program requires this.
    One option is to manually parse each row and insert into temp table that is basically definition of record (so record type no longer needed) and this becomes type of ref cursor. I can then simply select from the table. I'm not keen on this as it's just another object to worry about.
    Another option is to do some ugly instr/substr to extract each element in the sql statement (or write a function to do it but need to consider performance of this). The more generic the better as I need to reuse against multiple strongly typed ref cursors (kind of a contradiction in that by virtue of using strongly typed cursors I know exactly what I want returned!).
    Another option is for someone to shed some light on this as it must be possible to do in a simple way along the same lines I have started?
    thanks in advance

    That documentation seems to stay pretty vague. What constitutes the "right set of columns". Obviously my observed result matches what you are saying about not being able to enforce the datatypes in the fields of the strong typed cursor. But then I don't see the point of the strong typed cursor otherwise. Other sites i have read seem to focus on the %rowtype return rather than mapping it to a record. But the general consensus (at least to my understanding) is that if the cursor is strongly typed then the sql statement that used to open it must have the same set of columns and the datatypes must at least be able to implicitly convert.
    I will try the %rowtype strong ref cursor against a table and see if there is a different result. I am mainly interested in this because I would like to beable to ensure the datatype returned on the .net side through ODP
    I want to be able to know the datatype of a field coming back through a ref cursor at compile time not runtime. So it the answer to cast every field of the select statement?

Maybe you are looking for

  • Video drivers issue (dual DVI monitors off bay :: one black and white and one color)

    Hello,     I have tried everything to try to make these two monitors color. They are both relatively new Dell monitors. Both are DVI, both are connected to the latest Lenovo bay for my T430 laptop. Both worked fine after I initially installed both vi

  • Why can't I download TV episodes in Germany?

    Hi I would really like to know why Apple won't/can't offer downloads for Videos in Germany. It's very very frustrating to find your favorite show, only to see a certain iTunes Message which goes like 'The content you are requesting is not available i

  • Setting width/height of a control with CSS

    Hi, I am styling a button a button in CSS and set a background-image for the button in my stylesheet. The problem is, that the button should scale to the width/height of the image. I added: -fx-width: 32px; -fx-height: 32px; but it has no effect. I a

  • In which folder can I find the abap instance profile?

    Hi, In which folder can I find the abap instance profile? This is the parameter that I want to change: "profile parameter em/address_space_MB = 250 in the instance profile" Greets Stefan

  • "Internal Error" when Reader tries to open

    Hi all, "Internal Error" message shows up whenever a non admin user tries to open a PDF or the reader directly. Then i see this is the event logs. Event Type:    Error Event Source:    Application Error Event Category:    (100) Event ID:    1000 Date