Ref cursor question

Hi,
I have stored proc that takes pl/sql table as IN parameter and returns a ref cursor.
Data from pl/sql table is separated into two table type objects ... oType1 and oType2 based on some condition.
following works fine...
If oType1.Count > 0 then
     OPEN list_out FOR
     select col1, col2, col3, col4 ..... col20
     from TABLE(CAST(oType1 AS obj_table_t)) a,
     t1,
     t2
     where a.colvalue = t1.colvalue
     and etc....
UNION ALL
     select col1, col2, col3, col4 ..... col20
     from TABLE(CAST(oType1 AS obj_table_t)) a,
     t3,
     t4
     where a.colvalue = t3.colvalue
     and different conditions etc....
I have 4 UNION ALL's. Had to use this because of different where coditions.
end if..
The problem is with oType2......
If oType2.Count > 0 then
-- getting data from different database using dblink along with values from present database.
-- resultset columns will be same as above
-- Question is how to send these results in same refcursor.
end if;
Thanks for your time.

Hi,
I think that a plsql table is what you want and not a ref cursor. If you have a plsql table based on your user defined type you can keep assigning all the values you want to it and then pass it out of your procedure.
null

Similar Messages

  • ORA-01008 with ref cursor and dynamic sql

    When I run the follwing procedure:
    variable x refcursor
    set autoprint on
    begin
      Crosstab.pivot(p_max_cols => 4,
       p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by job order by deptno) rn from scott.emp group by job, deptno',
       p_anchor => Crosstab.array('JOB'),
       p_pivot  => Crosstab.array('DEPTNO', 'CNT'),
       p_cursor => :x );
    end;I get the following error:
    ^----------------
    Statement Ignored
    set autoprint on
    begin
    adsmgr.Crosstab.pivot(p_max_cols => 4,
    p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by
    p_anchor => adsmgr.Crosstab.array('JOB'),
    p_pivot => adsmgr.Crosstab.array('DEPTNO', 'CNT'),
    p_cursor => :x );
    end;
    ORA-01008: not all variables bound
    I am running this on a stored procedure as follows:
    create or replace package Crosstab
    as
        type refcursor is ref cursor;
        type array is table of varchar2(30);
        procedure pivot( p_max_cols       in number   default null,
                         p_max_cols_query in varchar2 default null,
                         p_query          in varchar2,
                         p_anchor         in array,
                         p_pivot          in array,
                         p_cursor in out refcursor );
    end;
    create or replace package body Crosstab
    as
    procedure pivot( p_max_cols          in number   default null,
                     p_max_cols_query in varchar2 default null,
                     p_query          in varchar2,
                     p_anchor         in array,
                     p_pivot          in array,
                     p_cursor in out refcursor )
    as
        l_max_cols number;
        l_query    long;
        l_cnames   array;
    begin
        -- figure out the number of columns we must support
        -- we either KNOW this or we have a query that can tell us
        if ( p_max_cols is not null )
        then
            l_max_cols := p_max_cols;
        elsif ( p_max_cols_query is not null )
        then
            execute immediate p_max_cols_query into l_max_cols;
        else
            RAISE_APPLICATION_ERROR(-20001, 'Cannot figure out max cols');
        end if;
        -- Now, construct the query that can answer the question for us...
        -- start with the C1, C2, ... CX columns:
        l_query := 'select ';
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        -- Now add in the C{x+1}... CN columns to be pivoted:
        -- the format is "max(decode(rn,1,C{X+1},null)) cx+1_1"
        for i in 1 .. l_max_cols
        loop
            for j in 1 .. p_pivot.count
            loop
                l_query := l_query ||
                    'max(decode(rn,'||i||','||
                               p_pivot(j)||',null)) ' ||
                                p_pivot(j) || '_' || i || ',';
            end loop;
        end loop;
        -- Now just add in the original query
        l_query := rtrim(l_query,',')||' from ( '||p_query||') group by ';
        -- and then the group by columns...
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        l_query := rtrim(l_query,',');
        -- and return it
        execute immediate 'alter session set cursor_sharing=force';
        open p_cursor for l_query;
        execute immediate 'alter session set cursor_sharing=exact';
    end;
    end;
    /I can see from the error message that it is ignoring the x declaration, I assume it is because it does not recognise the type refcursor from the procedure.
    How do I get it to recognise this?
    Thank you in advance

    Thank you for your help
    This is the version of Oracle I am running, so this may have something to do with that.
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.8.0 - Production
    I found this on Ask Tom (http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3027089372477)
    Hello, Tom.
    I have one bind variable in a dynamic SQL expression.
    When I open cursor for this sql, it gets me to ora-01008.
    Please consider:
    Connected to:
    Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
    JServer Release 8.1.7.4.1 - Production
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1;
      8  end;
      9  /
    declare
    ERROR at line 1:
    ORA-01008: not all variables bound
    ORA-06512: at line 5
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1, 2;
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    And if I run the same thing on 10g -- all goes conversely. The first part runs ok, and the second
    part reports "ORA-01006: bind variable does not exist" (as it should be, I think). Remember, there
    is ONE bind variable in sql, not two. Is it a bug in 8i?
    What should we do to avoid this error running the same plsql program code on different Oracle
    versions?
    P.S. Thank you for your invaluable work on this site.
    Followup   June 9, 2005 - 6pm US/Eastern:
    what is the purpose of this query really?
    but it would appear to be a bug in 8i (since it should need but one).  You will have to work that
    via support. I changed the type to tarray to see if the reserved word was causing a problem.
    variable v_refcursor refcursor;
    set autoprint on;
    begin 
         crosstab.pivot (p_max_cols => 4,
                 p_query => 
                   'SELECT job, COUNT (*) cnt, deptno, ' || 
                   '       ROW_NUMBER () OVER ( ' || 
                   '          PARTITION BY job ' || 
                   '          ORDER BY deptno) rn ' || 
                   'FROM   emp ' ||
                   'GROUP BY job, deptno',
                   p_anchor => crosstab.tarray ('JOB'),
                   p_pivot => crosstab.tarray ('DEPTNO', 'CNT'),
                   p_cursor => :v_refcursor);
    end;
    /Was going to use this package as a stored procedure in forms but I not sure it's going to work now.

  • Dynamic Ref Cursor report in 6i

    Hello,
    I apologise that this question is so similar to many in this forum, but I haven't found a solution to my problem yet.
    I've created a ref cursor query because I need to include a variable p_orgs in my WHERE clause, like so:
    where e.org_id in ('||p_orgs||')
    I've constructed the report as mentioned on this page:
    www.dulcian.com
    FAQs - SQL & PL/SQL FAQs - FAQ ID# 5:
    "How can you use 'dynamic' ref cursors in Oracle Reports 3.0 / 6i?"
    (Thanks to Zlatko Sirotic for the information).
    I get a compile error when compiling the package body that holds my ref cursor open statement:
    Error 103 Encountered the symbol ''select'' when expecting one of the following:
    Select
    Is there any way around this problem?
    If I was to upgrade to Reports 9i would it work?
    Many thanks,
    Hazel

    Hello,
    Just a remark : you don't need to use a Ref Cursor if you just want to use a "dynamic where clause".
    You can use a lexical reference :
    You can find examples at :
    http://www.oracle.com/webapps/online-help/reports/10.1.2/topics/htmlhelp_rwbuild_hs/rwwhthow/whatare/dmobj/sq_a_lexical_references.htm
    (This page is about Reports 10.1.2 but Lexical references are identical in Reports 6i and Reports 10.1.2)
    Regards

  • [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 print/store in file the ref cursor in pl/sql block ?

    How to print/store in file the ref cursor in pl/sql block ?.

    How to print/store in file the ref cursor in pl/sql block ?.You question is quite confusing?
    So, i'm providing link in this manner.
    For RefCursor,
    http://www.oracle-base.com/articles/misc/UsingRefCursorsToReturnRecordsets.php
    http://www.oracle.com/technology/oramag/code/tips2003/042003.html
    For UTL_FILE,
    http://www.morganslibrary.org/reference/utl_file.html
    Regards.
    Satyaki De.
    Updated with new morgan library link.
    Edited by: Satyaki_De on Feb 24, 2010 9:03 PM

  • Using CRUD procedures to update data and ref cursors to return data

    Hi:
    I am currently evaluating Apex 3.x to replace an existing app that uses lots of procedures to update and return data.
    1. Is it possible to return data from a function that returns a cursor (or from a procedure that has an input/output ref cursor parameter for that matter) ? Example: Let's say I have the following function in a package:
    function get_data return sys_refcursor
    is
    l_cursor sys_refcursor;
    begin
    open l_cursor for select sysdate as field from sys.dual;
    return l_cursor;
    end;
    Can I add a page with a table that is populated based on this function? Based on my research it is not possible, but I want an APEX expert to confirm it
    2. The old application uses CRUD procedures to update date, that is for each table there are 3 procedures, insert update and delete. Question: is it possible to channel all the update, inserts and deletes through these procedures? Furthermore, in lots of cases I use sequences to populate the primary keys, and the new value is returned as output parameter. Can I retrieve the output value and use it maybe in the next page I am branching to?
    In the samples that I've seen the same form is used for insert and update. How do I distinguish between the two modes?
    3. Can you please point me to some samples that show how to do 1 & 2. The standard samples that I've seen use the automatic row processing.
    4. Could you please recommend some good books about Apex or HTML db? I found the documentation unintuitive. It is hard to picture quickly how things tie together by reading this documention. I wish the documentation was more task oriented and presented 'how to...' implement generic patterns used in web apps.
    Thank you in advance

    Hi guys
    Check out the last 2 posts in this thread for ideas on how to implement 1.
    Report on user data from LDAP
    Varad

  • Problem in passing ref cursor values as parameter in where clau.Most Urgent

    Problem:
    1) I have used normal cursor (C_hubmsgid_set) with some select statement such as grouping and all.
    After executing the query it will return some resultset to the specified cursor.
    2) I am trying to use another cursor which is ref cursor but the problem is
    I want to give all the resultset based on all the conditions to the ref cursor.
    But the cursor will get only the last record due to overwriting .how to get all
    the result set in a ref cursor like
    cursor c1 is select .....
    loop
    open refcursor for
    Select * from ....where condition
    end loop
    After this the refcursor( p_sysaudithistory_cur) which should have all the resultset matched by the where condition.
    3. It should be java compatible one.
    4. I am not able to match cursor row = IN Pameter value
    Below is the query:
    CREATE OR REPLACE PROCEDURE SP_TEST_audit_history2 (
    p_start IN date,
    p_end IN date,
    p_msgcode IN varchar2,
    p_partnername IN varchar2,
    p_status IN varchar2,
    p_locationname IN varchar2,
    p_custbusunit IN varchar2,
    p_sysaudithistory_cur OUT plutotypes.ref_cursor,
    p_status1 OUT NUMBER) AS
    l_status NUMBER := 0;
    CURSOR C_hubmsgid_set IS
    SELECT DISTINCT MAX(tfm.datetime) datetime, tfm.hubmsgid
    FROM tfm_status tfm, vw_msgcode_part_locn vw
    WHERE
    tfm.datetime >= NVL(p_start, TO_DATE('01/01/1981','DD/MM/YYYY')) AND
    tfm.datetime <= NVL(p_end, TO_DATE('31/12/9999','DD/MM/YYYY')) AND
    tfm.msgcode LIKE NVL(p_msgcode,'%') AND
    vw.msgcode = tfm.msgcode
    AND vw.partnername LIKE NVL(p_partnername,'%')
    AND tfm.status LIKE NVL(p_status,'%')
    AND vw.locationname LIKE NVL(p_locationname,'%')
    AND vw.custbusunit LIKE NVL(p_custbusunit,'%')
    AND rownum < 250
    GROUP BY tfm.hubmsgid
    ORDER BY datetime DESC;
    /* Loop through the Cursor */
    BEGIN
    BEGIN
    OPEN p_sysaudithistory_cur
    FOR
    SELECT
    tfm.hubmsgid ,
    tfm.status || '-'|| nvl2(tfm.exception_id,'FAILED','OK') ,
    tfm.datetime,
    tfm.exception_id
    FROM tfm_status tfm
    WHERE tfm.hubmsgid = c_hubmsgids.hubmsgid /* here only i am getting error*/
    AND tfm.datetime = c_hubmsgids.datetime
    AND tfm.status like NVL(p_status,'%')
    and rownum =1;
    EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
    l_status := 1;
    END;
    p_status1 := l_status;
    END;
    Thanks in advance
    prasanth a.s.

    Please don't post duplicate questions. All it does is clutter the forums and result in fragmented threads and duplicate responses. Please see my response in the original thread at the link below.
    Please solve this Refcursor issue PLEASE

  • Need help with Ref Cursor

    Dear All,
    Version : '11.2.0.2.0'
    I have a procedure which gets called from a screen ( on .Net) if use pushes a particular button.
    The procedure takes 15 minutes to complete.
    My requirement is to intimate the front end(.Net) as soon as the procedures gets called successfully without waiting for its completion as it is going to take 15 mins.
    The reason being, the front end will popup a message saying that " The process is going to take long time, A mail will be sent to u after its completion"  once it has been intimated that the procedure has been called successfully.
    Could you please suggest can i return a cursor to front end without even manipulating the data.
    i hope my question is understandable.

    9876564 wrote:
    Dear All,
    Version : '11.2.0.2.0'
    I have a procedure which gets called from a screen ( on .Net) if use pushes a particular button.
    The procedure takes 15 minutes to complete.
    My requirement is to intimate the front end(.Net) as soon as the procedures gets called successfully without waiting for its completion as it is going to take 15 mins.
    The reason being, the front end will popup a message saying that " The process is going to take long time, A mail will be sent to u after its completion"  once it has been intimated that the procedure has been called successfully.
    Could you please suggest can i return a cursor to front end without even manipulating the data.
    i hope my question is understandable.
    It seems to me that your problem is not an Oracle one, but a user interface one.
    I'm assuming the slowness of the procedure is due to how long it's taking to query the data, and if you can't speed that up then, to have the procedure return a ref cursor, the connection between the front end and the procedure must be maintained (the process on Oracle must belong to a session, and the front end needs to be connected to that session).
    So, you can't have Oracle go off and start a seperate process and then pass back the ref cursor when it's finished, because even though you can spawn off seperate processes such as using DBMS_JOB or DBMS_SCHEDULER, they will run in their own 'session' and the calling code won't keep a hold on any of those sessions... they're effectively stand-alone and seperate.
    What you'll have to do is likely get your .net application to spawn off a child process to the main app, that presents the message saying it'll take some time, does the call to Oracle and waits for Oracle to return the resultant ref cursor, which it can then pass back to the main application etc.  Due to .net allowing for multi-tasking, that is where the split processing should take place.

  • Clarification in ref cursor.

    I have a procedure Pr_job1 with select and followed by insert statements.
    In pr_job1 I am using a ref cursor like open cursor for ‘statement’. This query takes a long time to execute ie more than 20 mins.
    To check the dynamically framed query I gave a insert to a dummy_tab table just below the cursor
    Like ..
    Open p_cv for ‘select statement’;
    Insert into dumm_tab (123,sysdate,’select statement’);
    Commit;
    Loop
    Fetch p_cv into m_rec;
    Exit when p_cv%notfound;
    Rest of the statements.
    End loop;
    In this case finally it gave an error after 20 mins
    Like
    sqlerrm ORA-01652: unable to extend temp segment by 128 in tablespace
    TEMP
    ORA-02063: preceding line from CARSDBP1
    I just checked the v$locked_objects before It gives the error. There I found a lock for the dummy_tab table. My question is will the query will execute for open cursor or while it executes the fetch statement. I ran the query alone in the sql plus window as a normal query. There also I got the table space error.
    Thanks in advance…….
    Regards,
    Jeeva

    user12128516 wrote:
    I have a procedure Pr_job1 with select and followed by insert statements.
    In pr_job1 I am using a ref cursor like open cursor for ‘statement’. This query takes a long time to execute ie more than 20 mins.
    To check the dynamically framed query I gave a insert to a dummy_tab table just below the cursor
    Like ..
    Open p_cv for ‘select statement’;
    Insert into dumm_tab (123,sysdate,’select statement’);
    Commit;
    Loop
    Fetch p_cv into m_rec;
    Exit when p_cv%notfound;
    Rest of the statements.
    End loop;
    In this case finally it gave an error after 20 mins
    Like
    sqlerrm ORA-01652: unable to extend temp segment by 128 in tablespace
    TEMP
    ORA-02063: preceding line from CARSDBP1
    I just checked the v$locked_objects before It gives the error. There I found a lock for the dummy_tab table. My question is will the query will execute for open cursor or while it executes the fetch statement. I ran the query alone in the sql plus window as a normal query. There also I got the table space error.
    Thanks in advance…….
    Regards,
    JeevaHow about you show us an exact copy / paste from SQLPLUS of what you are running? And perhaps you can clarify your question a bit. You have exceeded the allotted amount of space defined for the tablespace in which your table is located, so you should get your local DBA to allocate more space ....
    Aside from that, i'm not sure what your question is about table locking, there are many types of locks, and i have no idea what you viewed that made you suspect the table was locked....

  • Spliting SDO_JOIN in two ref cursors

    Hi,
    What is the best/most efficient way to return two ref cursor using a SDO_JOIN?
    In other words, from this example taken from the Oracle Spatial User Guide
    SELECT a.gid, b.gid FROM parks a, highways b,
    TABLE(SDO_JOIN('PARKS', 'SHAPE', 'HIGHWAYS', 'SHAPE',
    'mask=ANYINTERACT')) c
    WHERE c.rowid1 = a.rowid AND c.rowid2 = b.rowid;
    I would like to have a procedure that split the result of the above Select in two ref cursors. Something like this:
    PROCEDURE "GET_PARKS_HIGHWAYS"
    "P_PARKS" OUT SYS_REFCURSOR,
    "P_HIGHWAYS" OUT SYS_REFCURSOR
    as
    BEGIN
    /* Here I want every Parks that interact a highway
    OPEN P_PARKS FOR
    SELECT * FROM PARKS WHERE ....
    /* Here I want every highway that interact a park
    OPEN P_HIGHWAYS FOR
    SELECT * FROM HIGHWAYS WHERE ....
    END
    Can I do this with a single SDO_JOIN or do I have to put one in the where clause of each select?
    Hope that somebody understand! If not, let me know, I will try to be clearer.
    Thanks
    Frederic Goulet

    Hi Frederic,
    You will get the complete set of answers for both questions when using the anyinteract mask, i.e. you will have in your result set:
    All of the parks that interact with highways, and all of the highways that interact with parks.
    If you want, you can order by a.gid, and for each park you would see all of the highways.
    If you order by b.gid, for each highway you would see all the parks.
    The result set is complete in both cases.
    Hope this helps.

  • Open ref cursor in a procedure

    Hi
    I have a procedure which has 3 input parameters and 1 REF CURSOR type OUT parameter.
      In the body of the procedure a select query is dynamically being created, and just before the end of the procedure the REF CURSOR is opened for SELECT(dynamic) query
    For Ex: Create or replace procedure proc_name(a in number,b in number,c in number,RETVAL OUT REF CURSOR) as
    decalre
      strQry varchar2(3000);
    begin
       -- strQry is select query built dynamically
    OPEN RETVAL for strQry;
    end proc_name;
    This procedure is being called by a java application. My question is what the open cursor statement is doing in the procedure?
    Any ideas? Thanks!
    greddy

    Hi,
    As i know, for example if we want to generate a report for some particular records in our project.consider we are using java as front end and oracle as backend. ok. In that case we need to bring the data from backend to front end ,for that in backend (oracle) we can write procedure to perform this task using ref cursors.
    Note: ref cursor will provide the most efficient way in bringing the records from back end to front end.
    Create or replace procedure proc_name(a in number,b in number,c in number,RETVAL OUT REF CURSOR) as
    decalre
    strQry varchar2(3000);
    begin
    -- strQry is select query built dynamically
    --if we are using dynamic query, we can filter out the records using id or name or date
    once we did, we need to pass the values to calling enviroment, since we declared the ref cursor as out parameter, we can use the ref cursor to pass the values to calling enviroment. Since we are using ref cursor we need to open the cursor for that dynamic query.
    OPEN RETVAL for strQry;
    end proc_name;
    hope this information is some what helpful. if you got any details regarding this please post it..
    thanks.

  • Ref Cursors in a stored Procedure

    Can some help me with an answer to the below question.
    How many ref cursors can be declared in a stored procedure in oracle?
    Thanks

    user533016 wrote:
    You are right. Keeping so many cursors open is not good at all. But i was doing this to see where it breaks and is there something that definitely controls the number of refcursors in allowed a PL/SQL block.As Karthick already mentioned you have the OPEN_CURSORS parameter which defines how many open cursors you may have in any one session.
    However, this doesn't just apply to Ref Cursors. If you open explicitly defined cursors then this will also count towards that, as well as issuing select statements as they are implicit cursors... e.g.
    declare
      cursor c1 is
        select * from emp;
      cursor c2 is
        select * from dept;
      v_c1 c1%ROWTYPE;
      v_c2 c2%ROWTYPE;
      v_cnt number;
    begin
      open c1; -- now we have 1 open cursors
      loop
        fetch c1 into v_c1;
        exit when c1%notfound;
        open c2;  -- now we have 2 open cursors
        loop
          fetch c2 into v_c2;
          exit when c2%notfound;
          select count(*)  -- this counts as opening cursor number 3.
          into v_cnt
          from payroll;
          -- after the select statement the implicit cursor is automatically closed, so now we have 2 open again
        end loop;
        close c2; -- after this we just have 1 more open
      end loop;
      close c1; -- after this we have no open cursors
    end;

  • Using Ref Cursors as region source

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

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

  • Returning a Ref cursor as an OUT Parameter

    Hi Guys
    I have defined 2 Types and 2 Ref cursors as shown below.I have written a procedure having 2 IN and 2 OUT parameters which are of type Ref cursors and return records to the calling client. My question is how can i test for the output of the two cursors here in pl/sql?.. also i should not close the sursors.. right?..its the job of the calling client as per my knowledge....Please suggest
    TYPE type_dept_Rec IS RECORD(deptNo varchar2);
    TYPE type_prod_Rec IS RECORD(prodType varchar2);
    TYPE deptCursor IS REF CURSOR RETURN type_dept_Rec;
    TYPE prodCursor IS REF CURSOR RETURN type_prod_Rec;
    PROCEDURE TEST (pinCode IN varchar2, prodType IN number, deptCursor OUT deptType, productCursor OUT deptType) IS
    BEGIN
    OPEN deptCursor FOR SELECT
    deptNo
    from
    DEPT
    where
    pinCode = pinCode;
    OPEN productCursor FOR SELECT
    prodCode
    from
    PROD
    where
    prodType = prodType;
    end;

    A Correction to the above code snippet
    Hi Guys
    I have defined 2 Types and 2 Ref cursors as shown below.I have written a procedure having 2 IN and 2 OUT parameters which are of type Ref cursors and return records to the calling client. My question is how can i test for the output of the two cursors here in pl/sql?.. also i should not close the sursors.. right?..its the job of the calling client as per my knowledge....Please suggest
    TYPE type_dept_Rec IS RECORD(deptNo varchar2);
    TYPE type_prod_Rec IS RECORD(prodType varchar2);
    TYPE deptCursor IS REF CURSOR RETURN type_dept_Rec;
    TYPE prodCursor IS REF CURSOR RETURN type_prod_Rec;
    PROCEDURE TEST (pinCode IN varchar2, prodType IN number, deptCursor OUT deptCursor, productCursor OUT prodCursor) IS
    BEGIN
    OPEN deptCursor FOR SELECT
    deptNo
    from
    DEPT
    where
    pinCode = pinCode;
    OPEN productCursor FOR SELECT
    prodCode
    from
    PROD
    where
    prodType = prodType;
    end

  • Ref Cursors

    I was looking at this example given for ref cursor
    CREATE TABLE employees (
    empid NUMBER(5),
    empname VARCHAR2(30));
    INSERT INTO employees (empid, empname) VALUES (1, 'Dan Morgan');
    INSERT INTO employees (empid, empname) VALUES (2, 'Hans Forbrich');
    INSERT INTO employees (empid, empname) VALUES (3, 'Caleb Small');
    COMMIT;
    CREATE OR REPLACE PROCEDURE pass_ref_cur(p_cursor SYS_REFCURSOR) IS
    TYPE array_t IS TABLE OF VARCHAR2(4000)
    INDEX BY BINARY_INTEGER;
    rec_array array_t;
    BEGIN
    FETCH p_cursor BULK COLLECT INTO rec_array;
    FOR i IN rec_array.FIRST .. rec_array.LAST
    LOOP
    dbms_output.put_line(rec_array(i));
    END LOOP;
    END pass_ref_cur;
    set serveroutput on
    DECLARE
    rec_array SYS_REFCURSOR;
    BEGIN
    OPEN rec_array FOR
    'SELECT empname FROM employees';
    pass_ref_cur(rec_array);
    CLOSE rec_array;
    END;
    In this P_cursor is weaklytyped ref cursor. My question is
    1. How does the fetch identifies which columns are there in the cursor ?
    2. If I add another column (say empid) to cursor query it is throwing error message !
    3. In my case; I need to use the cursor columns for futher processing in my proc. In such cases how do we define the cursor ?
    TIA

    1. How does the fetch identifies which columns are there in the cursor ?It doesn't. It just puts the first value into the first variable, the second into the next and so on. If it doesn't fit you get an exception (as you found).
    In fact a strongly typed ref cursor is the same underneath, it just makes your code declare things slightly more specifically.
    2. If I add another column (say empid) to cursor query it is throwing error message !You would have to modify the target variable and the fetch to match the cursor.
    3. In my case; I need to use the cursor columns for futher processing in my proc. In such cases how do we define the cursor ?You have to know what columns you are fetching so that you can do something with them. Even if you parsed it out (as SQL*Plus does when it prints a refcursor variable for example) the rest of your code would need to know what it was referring to, how many columns, their datatypes etc.

Maybe you are looking for

  • Color Management Settings in Windows 7/Vista

    I know this is not exactly the right forum to ask, but I also know that some people very knowledgable in color managment read/write here: Can somebody explain to me what the setting of "Device Profile" in "Windows Color System Defaults" really does/a

  • Can we run java programms on Windows XP?

    Hi experts.. I installed JDK on Microsoft Windows XP Home Edition..but i am unable to run java programmes. can i run java programmes on Windows XP?? if so how?? i will be very thankful..if any one solve this problem..

  • Smart chip registration failure

    Help,  I have a new Nokia 2610 that won't charge plus just saw a message flash quickly on the screen that said "smart chip registration failed" Then the screen went black again as it's been ever since I plugged it in to charge the new battery in the

  • Enable Variant Config. screen in VA01/VA21

    Hi, I want to create a Quotation/Order in VA21/VA01 with a configurable material. But the configuration screen of VA21 is in disabled mode and not accepting input. Is there any settings missing for that screen? Please help in this regard. Thanks & Re

  • Screen shaking on 2nd display

    had my imac for about a month now and just connected to my 26inch sony hd lcd through the vga input and sometimes the screen shakes ever so slightly. does anyone know what could be causing this? i have a gig of ram and the 256mb graphics card. it is