URGENT - Dive into BC4J related -- REF CURSOR

Hi,
I am trying out the example as provided by Steve in his article. This is what I've as of now:
1. Created a VO based on EMP.
2. Added custom code to ViewImpl.java file.
3. Created a browse JSP (BC4J based).
Now I want to be able to pass the passmeter for dept no from JSP. So, I used
<jbo: SetWhereClauseParam index="0" value="10" datasource="ds">
First of all, I get nothing in JSP when I use index=0. If I change index from 0 to 1, then I get all the records (from various depts.) which means that the parameter is not been used.
Can someone please help me.
Thanks,
Jatinder

I've tried exactly this and it works.
Try what you find in this zip file:
http://www.geocities.com/smuench/RefCursorVO.zip

Similar Messages

  • Dive into BC4J related  --REF CURSOR

    I read through the article (Dive into BC4J )and generated several questions:
    1)If I have to execute a ref cursor:
    private static final String SQL =
    "begin ? := RefCursor.getSomthing(?, ?);end;";
    Now I need to pass two parameters to the stored procedure,
    assume first is ID varchar2, second Name varchar2
    In my client code: I use vo.executeQuery()
    then how can I pass these two parameters? (so that the executeQueryForCollection(Object qc,Object[] params,int numUserParams) can use them)
    NOTES: The viewobject I created is not based on any sql statement, but an expert mode, i.e., I created the attributes myself.
    2)createRowFromResultSet(...) function calls
    populateAttributeForRow(r,0, nullOrNewNumber(rs.getBigDecimal(1)));
    If there are more than one rows in the reseultset, will
    this function be called "automatically" by the frame work to iterate through each every row in the resultset?
    Thanks.
    Scott

    In short, yes. :-)

  • Selecting the contents of a table(collection) into a strong REF Cursor

    I'm trying to roll some data into a table collection and return it as a strong named cursor.
    I have not been able to do this successfully yet.
    I have tried casting the table and I couldn't get that to work either.
    I have included the whole procedure but here is the line I am getting errors on:
    SELECT * bulk collect into o_response_data_cur from table (response_data_tbl);
    Any help on this would be great.
    P.S. - As this is being picked up by BizTalk I can't return a table.
    Thanks,
    Todd M
    PROCEDURE create_customer (
    i_interface_hdr IN BizTalk_TestCustomer.interface_hdr_rec,
    i_customer_rec IN BizTalk_TestCustomer.customer_rec,
    i_address_cur IN BizTalk_TestCustomer.CUR_Addresses,
    i_contact_cur IN BizTalk_TestCustomer.CUR_Contact,
    o_interface_status OUT varchar2,
    o_response_data_cur OUT BizTalk_TestCustomer.CUR_CreateCustResponse)
    IS
    l_response_rec create_cust_response_rec;
    response_data_tbl create_cust_response_tbl;
    BEGIN
    FOR i IN 1 .. 10
    LOOP
    l_response_rec.ERROR_TYPE := 'Pre-Validation Error';
    l_response_rec.ERROR_CODE := 'DUMMY-' || i;
    l_response_rec.error_message := 'Test Error Message-' || i;
    response_data_tbl (i) := l_response_rec;
    END LOOP;
    SELECT * bulk collect into o_response_data_cur from table (response_data_tbl);
    o_interface_status := 'FAILURE';
    END create_customer;
    END BizTalk_TestCustomer;
    Here is the important Spec info:
    TYPE create_cust_response_rec
    IS
    RECORD (
    orig_system_party_ref varchar2 (240),
    orig_system_cust_acct_ref varchar2 (240),
    orig_system_site_ref varchar2 (240),
    oracle_party_id number,
    oracle_customer_id number,
    oracle_site_id number,
    ERROR_TYPE strar_cust_intf_err.ERROR_TYPE%TYPE,
    ERROR_CODE strar_cust_intf_err.ERROR_CODE%TYPE,
    error_message strar_cust_intf_err.error_message%TYPE
    TYPE CUR_Addresses IS REF CURSOR RETURN BizTalk_TestCustomer.address_rec;
    TYPE CUR_Contact IS REF CURSOR RETURN BizTalk_TestCustomer.contact_rec;
    TYPE CUR_CreateCustResponse IS REF CURSOR RETURN BizTalk_TestCustomer.create_cust_response_rec;
    TYPE create_cust_response_tbl
    IS
    TABLE OF create_cust_response_rec
    INDEX BY binary_integer;

    I think this is one of the most complicated one to develop and execute perfectly. ;)
    Here is one such case ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    Elapsed: 00:00:00.55
    satyaki>
    satyaki>
    satyaki>create or replace type d_obj as object
      2    (
      3      buff    varchar2(310)
      4    );
      5  /
    Type created.
    Elapsed: 00:00:00.05
    satyaki>
    satyaki>
    satyaki>create or replace type d_rec as table of d_obj;
      2  /
    Type created.
    Elapsed: 00:00:01.14
    satyaki>
    satyaki>
    satyaki>
    satyaki>
    satyaki>create or replace function pipe_buff(e_sal in number)
      2  return d_rec
      3  pipelined
      4  is
      5    cursor c1
      6    is
      7      select d_obj(
      8                    ename||' Joined On '||to_char(hiredate,'DD-MON-YYYY hh24:mi:ss')
      9                  ) str
    10      from emp
    11      where sal > e_sal;
    12     
    13   r1 c1%rowtype;
    14  begin
    15    for r1 in c1
    16    loop
    17      pipe row(r1.str);
    18    end loop;
    19    return;
    20  end;
    21  /
    Function created.
    Elapsed: 00:00:01.69
    satyaki>
    satyaki>
    satyaki>
    satyaki>create or replace procedure gen_cur_pipe(
      2                                            s_sal in number,
      3                                            rc in out sys_refcursor
      4                                          )
      5  is  
      6    str1  varchar2(500);
      7  begin  
      8    str1 := 'select *           
      9             from table(cast(pipe_buff('||s_sal||') as d_rec))';           
    10  
    11   open rc for str1;  
    12  exception  
    13    when others then    
    14      dbms_output.put_line(sqlerrm);
    15  end;
    16  /
    Procedure created.
    Elapsed: 00:00:00.05
    satyaki>
    satyaki>
    satyaki>
    satyaki>create table test_dual
      2    (
      3      dummy    varchar2(310)
      4    );
    Table created.
    Elapsed: 00:00:00.10
    satyaki>
    satyaki>
    satyaki>
    satyaki>declare   
      2    rec_x test_dual%rowtype;   
      3    w sys_refcursor;
      4  begin  
      5    dbms_output.enable(1000000);  
      6    gen_cur_pipe(&num,w);  
      7    loop    
      8      fetch w into rec_x;     
      9       exit when w%notfound;             
    10         dbms_output.put_line('Employee Special Deatils: '||rec_x.dummy);
    11    end loop;  
    12    close w;
    13  exception  
    14    when others then    
    15      dbms_output.put_line(sqlerrm);
    16  end;
    17  /
    Enter value for num: 1000
    old   6:   gen_cur_pipe(&num,w);
    new   6:   gen_cur_pipe(1000,w);
    Employee Special Deatils: SATYAKI Joined On 02-NOV-2008 12:07:30
    Employee Special Deatils: SOURAV Joined On 14-SEP-2008 00:07:21
    Employee Special Deatils: WARD Joined On 22-FEB-1981 00:00:00
    Employee Special Deatils: JONES Joined On 02-APR-1981 00:00:00
    Employee Special Deatils: MARTIN Joined On 28-SEP-1981 00:00:00
    Employee Special Deatils: BLAKE Joined On 01-MAY-1981 00:00:00
    Employee Special Deatils: CLARK Joined On 09-JUN-1981 00:00:00
    Employee Special Deatils: SCOTT Joined On 19-APR-1987 00:00:00
    Employee Special Deatils: KING Joined On 17-NOV-1981 00:00:00
    Employee Special Deatils: TURNER Joined On 08-SEP-1981 00:00:00
    Employee Special Deatils: ADAMS Joined On 23-MAY-1987 00:00:00
    Employee Special Deatils: FORD Joined On 03-DEC-1981 00:00:00
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.30
    satyaki>
    satyaki>
    satyaki>/
    Enter value for num: 4000
    old   6:   gen_cur_pipe(&num,w);
    new   6:   gen_cur_pipe(4000,w);
    Employee Special Deatils: SATYAKI Joined On 02-NOV-2008 12:07:30
    Employee Special Deatils: SOURAV Joined On 14-SEP-2008 00:07:21
    Employee Special Deatils: CLARK Joined On 09-JUN-1981 00:00:00
    Employee Special Deatils: KING Joined On 17-NOV-1981 00:00:00
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.13
    satyaki>I'm not so sure about the performance.
    Regards.
    Satyaki De.

  • "Dive into BC4J" by Steve Muench

    Hi Steve,
    We use View objects mapped to entity objects. I created the default view object, set the bind var style to ? and created static strings for the various where clauses.
    The where clauses then get set during runtime.
    In your white paper you stated that if the where clause has to be set during runtime the way to go is with the ? style bind var.
    Later you state that if we use the Oracle jdbc driver then the :1 oracle style is the way to go.
    My questions:
    1. What i understand out of this is that i must change the bind var style to :1 etc, since we use the oracle jdbc driver??
    2. What exactly happens when the where-clause gets set to the same static string with only the bind variables changing? Does the re-parse/QueryPlan get triggered on the setWhereClause()??
    Or does the DB recognise the query as one that's been performed before and skips the formalities??
    Thanks in advance.

    1. What i understand out of this is that i must change the bind var style to :1 etc, since we use the oracle jdbc driver??
    you'll get better performance with Oracle-style bind variables.
    2. What exactly happens when the where-clause gets set to the same static string with only the bind variables changing?
    you wouldn't reset the where clause here, only reset the bind variables.
    In terms of API's, I mean that you'd call setWhereClauseParams() but not call setWhereClause() if the string of the where clause is not changing.
    Does the re-parse/QueryPlan get triggered on the setWhereClause()??
    resetting the where clause will cause BC4J to throw out the JDBC prepared statement and re-create it with the new statement.
    There are two things going on here.
    a. reuse of jdbc prepared statements
    b. reuse of SGA parsed sql statements
    If anything in the text of the sql changes (even one extra space!), then the DB SGA will need to reparse the query, doing checks on access rights and query plan etc.
    It's best not to change the SQL statement, and only reset the bind variable values.
    Or does the DB recognise the query as one that's been performed before and skips the formalities??
    It tries to.
    Bottom line, don't bother to reset the where clause if it's not really changing.

  • [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 accumlate resultsets in ref cursor

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

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

  • Ref cursor to another Ref cursor.

    Actually I have a ref cursor in a package x which has a procedure y.
    y has 4 parameters like procedure(a,b,c,d in out ref cursor type)
    I have another standalone procedure which has a ref cursor as out parameter and a,b,c as other parameters.
    This stand alone procedure implicitly calls the package procedure as x.y(a,b,c,d) d is a ref cursor defined in the stand alone procedure which is populated by the package's y procedure.
    My issue is that how to populate the standalone procedure's ref cursor with the value of the package's procedure's ref cursor with out using a temporary table?
    Please help me in this regard. It is urgent.

    Actually I have a ref cursor in a package x which has a procedure y.
    y has 4 parameters like procedure(a,b,c,d in out ref cursor type)
    I have another standalone procedure which has a ref cursor as out parameter and a,b,c as other parameters.
    This stand alone procedure implicitly calls the package procedure as x.y(a,b,c,d) d is a ref cursor defined in the stand alone procedure which is populated by the package's y procedure.
    My issue is that how to populate the standalone procedure's ref cursor with the value of the package's procedure's ref cursor with out using a temporary table?
    Please help me in this regard. It is urgent.

  • Ref cursor call across databases

    Hi,
    There is an oracle database for application X and another oracle database for application Y.
    From appX they are declaring a refcursor in a pkg:
    create or replace package getemp_info as
    TYPE v_cur IS REF CURSOR;
      PROCEDURE Getemp(curemp OUT t_cursor);
    end getemp_info;I understand what is done here.
    Now, from database Y I am supposed to open and fetch the values from curemp refcursor and populate it in my emp_new table.
    Is this what I have to do or is there something more to it. Pls advice:
    create or replace procedure set_emp as
    g_cur curemp; --what type should the variable be t_cursor/curemp?
    emp_rec myschema.emp%rowtype;
    begin
    open g_cur for select * from  myschema.emp --myschema.mytablename? --not sure of this
    loop
    fetch curemp into emp_rec;
    exit when curemp%notfound;
    end loop;
    close curemp;
    end;oracle 9i. And the table emp in X and Y have the same structure.
    My question is commented in the query above.
    in my database Y what variable should i declare to receive the refcursor?
    Pls help. Thnks in advance.
    Edited by: user254668 on Jan 14, 2011 1:20 PM

    Thanks Justin....
    Sorry if I confused you.
    1) Yes. I believe both are of th esame type. Either ways I am not bothered about what is happening in database X. The application people are going to create teh cursors and give.
    2) the set_emp procedure from database Y is supposed to use the records passed in the ref_cursor and insert it in its local table.
    To insert in a local table I needed to create a record into which the ref cursor record can be passed on to. That is why I created emp_rec record.
    I wanted to know if what I had written in the set_emp procedure was correct or needed correction. Pls suggest how I should open and fetch the ref cursor and most importantly how to declare the ref cursor.
    Hope I am clear now. Please let me know. Thnx!

  • How to put a collection into a Ref Cursor?

    Hi,
    I am trying to create a procedure (inside a package) which fills a collection and I need to fill a ref cursor (out parameter) with this collection. I can fill the collection but I how can I fill the ref cursor? I am receiving the message "PL/SQL: ORA-00902: invalid datatype" (Highlighted below as comments)
    I have a limitation: I am not allowed to create any kind of objects at the database schema level, so I have to create them inside the package. I'm writting it with SQL Tools 1.4, I'm also not allowed to do this in SQL+.
    This is the code of the package. The cursors' selects were simplified just because they are not the problem, but their structure is like follows below.
    CREATE OR REPLACE PACKAGE U3.PKG_TESTE AS
    TYPE REC_TYPE IS RECORD(
    COL1 VARCHAR2(50) ,
    COL2 VARCHAR2(100) ,
    COL3 VARCHAR2(20) ,
    COL4 VARCHAR2(30) ,
    COL5 VARCHAR2(100) ,
    COL6 VARCHAR2(50) ,
    COL7 NUMBER(3) ,
    COL8 VARCHAR2(30) ,
    COL9 VARCHAR2(16) ,
    COL10 VARCHAR2(50) ,
    COL11 NUMBER(4) ,
    COL12 VARCHAR2(40)
    TYPE REC_TYPE_LIST IS TABLE OF REC_TYPE
    INDEX BY BINARY_INTEGER;
    TYPE C_RESULTSET IS REF CURSOR;
    VAR_TAB_TESTE     REC_TYPE_LIST;
    PROCEDURE     Z_REC_INSTANCE
    pUSER_SYS_CODE VARCHAR2,
    pSYS_SEG_CODE VARCHAR2,
    pComplFiltro VARCHAR2,
    pCodInter NUMBER,
    cResultset out C_RESULTSET
    END PKG_TESTE ;
    CREATE OR REPLACE PACKAGE BODY U3.PKG_TESTE
    AS
    PROCEDURE Z_REC_INSTANCE
    pUSER_SYS_CODE varchar2,
    pSYS_SEG_CODE varchar2,
    pComplFiltro varchar2,
    pCodInter number
    AS
    cursor cur1 is
    select 'A' COL1, 'B' COL2, 'C' COL3, 'D' COL4, 'E' COL5,
    'F' COL6, 'G' COL7, 'H' COL8
    FROM DUAL;
    regCur1 cur1%rowtype;
    cursor cur2 is
    SELECT 'I' C1, 'J' C2, 'K' C3, 'L' C4
    FROM DUAL;
    regCur2 cur2%rowtype;
    varSQL varchar2(4000);
    varCOL10s varchar2(100);
    varFiltroAtrib varchar2(100);
    varCount number(10);
    BEGIN
    varCount := 1;
    open cur1;
    Loop
    fetch cur1 into regCur1;
    exit when cur1%notfound;
    open cur2;
    Loop
    fetch cur2 into regCur2;
    exit when cur2%notfound;
    VAR_TAB_TESTE(varCount).COL1 := regCur1.COL1;
    VAR_TAB_TESTE(varCount).COL2 := regCur1.COL2;
    VAR_TAB_TESTE(varCount).COL3 := regCur1.COL3;
    VAR_TAB_TESTE(varCount).COL4 := regCur1.COL4;
    VAR_TAB_TESTE(varCount).COL5 := regCur1.COL5;
    VAR_TAB_TESTE(varCount).COL6 := regCur1.COL6;
    VAR_TAB_TESTE(varCount).COL7 := regCur1.COL7;
    VAR_TAB_TESTE(varCount).COL8 := regCur1.COL8;
    VAR_TAB_TESTE(varCount).COL9 := regCur2.C1;
    VAR_TAB_TESTE(varCount).COL10 := regCur2.C2;
    VAR_TAB_TESTE(varCount).COL11 := regCur2.C3;
    VAR_TAB_TESTE(varCount).COL12 := regCur2.C4;
    varCount := varCount + 1;
    end Loop;
    end Loop;
    -- I'd like to do something like this:
    -- c_resultset := select * from var_tab_teste;
    -- but i don't know how to put the records of the type on the ref cursor,
    -- probably because I don't know how to select them
    -- pl/sql: ora-00902: invalid datatype
    for varCount in (select COL1 from table( CAST ( VAR_TAB_TESTE AS REC_TYPE_LIST ) ))
    loop
    dbms_output.put('WORKS');
    end loop;
    END Z_REC_INSTANCE;
    END PKG_TESTE;
    SHOW     ERR     PACKAGE          PKG_TESTE;
    SHOW     ERR     PACKAGE BODY     PKG_TESTE;
    SHOW     ERR     PROCEDURE     PKG_TESTE.Z_REC_INSTANCE;
    I'm using:
    Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    Thanks in advance.

    I don't have the exact version but in 9iOK I lied, I found a 9i instance ;-)
    Oracle9i Enterprise Edition Release 9.2.0.7.0 - 64bit Production
    JServer Release 9.2.0.7.0 - Production
    SQL> CREATE TABLE table_name (column_name VARCHAR2 (30));
    Table created.
    SQL> INSERT INTO table_name VALUES ('value one');
    1 row created.
    SQL> INSERT INTO table_name VALUES ('value two');
    1 row created.
    SQL> COMMIT;
    Commit complete.
    SQL> CREATE OR REPLACE PACKAGE package_name
      2  AS
      3     TYPE collection_type_name IS TABLE OF table_name%ROWTYPE;
      4
      5     FUNCTION function_name
      6        RETURN collection_type_name PIPELINED;
      7  END package_name;
      8  /
    Package created.
    SQL> CREATE OR REPLACE PACKAGE BODY package_name
      2  AS
      3     FUNCTION function_name
      4        RETURN collection_type_name PIPELINED
      5     IS
      6     BEGIN
      7        FOR record_name IN (SELECT column_name
      8                            FROM   table_name) LOOP
      9           PIPE ROW (record_name);
    10        END LOOP;
    11
    12        RETURN;
    13     END function_name;
    14  END package_name;
    15  /
    Package body created.
    SQL> VARIABLE variable_name REFCURSOR;
    SQL> BEGIN
      2     OPEN :variable_name FOR
      3        SELECT column_name
      4        FROM   TABLE (package_name.function_name);
      5  END;
      6  /
    PL/SQL procedure successfully completed.
    SQL> PRINT variable_name;
    COLUMN_NAME
    value one
    value two
    SQL>I recommend though that you test this thoroughly. There were bugs with this approach when it was newly introduced that prevented you from dropping the package.

  • Reg. Converting a package level cursor into a Ref cursor

    Hi Guru's,
    I am in need of converting a package level cursor which contains "FOR UPDATE OF" clause into a Ref cursor where the query will be dynamically built in with the needed table name and other parameters.
    Using that cursor many Update statement's were performed with "WHERE CURRENT OF" clause included in it.
    Now I changed my cursor into Ref cursor, but when i compile the cursor that is built dynamical is not identified, since i am getting error.
    Can any one tell me how to proceed in order to implement it?
    Do I need only go for dynamic bulding of the whole procedure.
    With Best Regards,
    Vijayasekaran.N

    May be you can work it around with ROWID. Like this
    Say this is your actual code.
    declare
         cursor c
         is
         select *
           from t
            for update of name;
         lno t.no%type;
         lname t.name%type;
    begin
         open c;
         loop
              fetch c into lno, lname;
              exit when c%notfound;
              update t set name = lno||lname
               where current of c;
         end loop;
         close c;
    end;
    /With refcursor you can do this.
    declare
         type rc is ref cursor;
         c rc;
         lno t.no%type;
         lname t.name%type;
         lrowid rowid;
    begin
         open c for 'select rowid rid, t.*
                   from t
                    for update of name';
         loop
              fetch c into lrowid,lno, lname;
              exit when c%notfound;
              update t set name = lno||lname
               where rowid = lrowid;
         end loop;
         close c;
    end;
    /Edited by: Karthick_Arp on Dec 26, 2008 2:00 AM

  • Ref Cursor - How to append records into ref cursor?

    Hi,
    Is it possible to append ref cursor?
    Iam having a procedure which accepts 1 string as input
    parameter. That string will have list of ID delimited by comma.
    I want to extract & match every ID with some tables.
    My problem is for first ID i would get 10 records
    and for 2nd ID i 'l get other 20 records. But while returning
    i need to send the same(10 + 20 records) as ref cursor(OUT parameter).
    But in below given code i could send only last 20 records. first
    10 records are not append/updated into ref cursor.
    How to append 2nd 20 records with 1st 10 records? so that i can
    send all the 30 records.
    Here goes my code...
    CREATE OR REPLACE PROCEDURE getCRMGroupsAndRollups_PRC
    in_groupId IN VARCHAR2,
    out_getCRMGroups OUT TYPES.DATASET
    IS
    v_temp VARCHAR2(500) := in_groupId ||',';
    v_temp_split VARCHAR2(500);
    v_pos1 NUMBER := 0;
    v_pos2 NUMBER := 1;
    v_pos3 NUMBER := 0;
    v_extract_char VARCHAR(1) := NULL;
    v_comma_cnt NUMBER := 0;
    BEGIN
    -- check in for null input parameters
    IF ( in_groupId IS NOT NULL ) THEN
    -- loop to count no of in_groupId
    FOR j IN 1..LENGTH(v_temp)
    LOOP
         v_extract_char := SUBSTR(v_temp,j,1);
         IF (v_extract_char = ',') THEN
              v_comma_cnt := v_comma_cnt + 1;
         END IF;     
    END LOOP;
    -- loop to extract in_group Id
    FOR i IN 1..v_comma_cnt
    LOOP
         v_pos1 := instr(v_temp,',',(v_pos1 + 1));
         v_pos3 := ((v_pos1-1) - v_pos2 )+ 1;
         v_temp_split := SUBSTR(v_temp,v_pos2,v_pos3);
         v_pos2 := v_pos1 + 1;
    -- query to return dataset filled BY list of all the current
    -- CRM groups and the associated rollup groups
    OPEN out_getCRMGroups FOR
    SELECT
    DISTINCT
    gcs.crm_st_id_cd,
    gcs.lgcy_roll_up_grp_num,
    gcs.lgcy_roll_up_grp_name,
    gcs.grp_xwalk_complt_dt,
    gcs.crm_grp_num,
    gcs.facets_gnat_id,
    gcs.crm_grp_name
    FROM
    grp_convsn_stat gcs
    --lgcy_xref_elem lxe
    WHERE
    ( gcs.mbrshp_convsn_aprvl_dt = NULL )
    OR ( gcs.mbrshp_convsn_aprvl_dt < (SYSDATE - 7 ) )
    AND ( gcs.facets_grp_stat_actv_ind = 'Y' )
    AND ( gcs.lgcy_roll_up_grp_num = v_temp_split );
    END LOOP;
    END IF;
    EXCEPTION
    WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('INTERNAL ERROR');
    END getCRMGroupsAndRollups_PRC;
    in this v_temp_split will have extracted id & iam opening
    ref cursor for each & every ID extracted from list.
    2) How to handle no_data_found exception for this ref cursor?
    Please help me....
    -thiyagarajan.

    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:110612348061
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:210612357425
    Message was edited by:
    Kamal Kishore

  • What is the better approach to populate Ref cursor into ADF business Component

    HI All,
    I have a requirement where I get the search results by joining more than 10 tables for my search criteria.
    What is the best approach to populate into ADF BCs.
    I have to go with Stored Procedure approach where I input the search Criteria and get the cursor back from the same.
    If I populate VO programmatically then the filtering at column level is a challenge.
    Anyone Please help me. Thanks in Advance.
    Thanks,
    Balaji Mucheli.

    The number of tables to be joined for a VO's query shouldn't matter - if the query is valid and fixed.
    Are you saying that you have logic to decide which tables to join to create the correct query?  I admit that would be a difficult thing to do, other than with a programmatic VO.  However, there are two possible solutions for doing this without a programmatic VO.
    Instead of your procedure returning a REF CURSOR, you can create an object type (CREATE TYPE) and a nested table of that type.  Then you have a function that returns an instance of the nested table.  The query in the VO is SELECT my_column... FROM TABLE(CAST my_table_function(:bind_variable) AS my_table_type).  You may have trouble getting the VO to accept this query as valid SQL, but it IS valid and it DOES work.
    Create a VO to be the master VO - it should have all the attributes that you intend to use, but the query can be anything, even a SELECT from DUAL.  Then create other VOs that subclass the master VO - one for each major variation of the query.  When you use the VO, use the data control for the master VO to create your pages, but change the pageDef to make the VO name a variable (with expression language).  Then you can set that variable to the correct child VO for the query that needs to execute.

  • Dynamic REF Cursor with Dynamic Fetch - Urgent

    i have a pl/sql package with generates dynamic SQL statments. my problem is i want to open this SQL statment dynamically and fetch data in dynamic variable.
    declare
    type type_temp is REF CURSOR;
    cur_temp type_temp;
    mv_sql varchar2(4000);
    begin
    -- this will be dunamically generated and
    -- hence could have any no. of columns.
    mv_sql := select f1, f2, f3, f4 from table_temp;
    open cur_temp for mv_sql;
    fetch cur_temp into c1, c2, c3, c4;
    close cur_temp;
    end;
    problem is my sql statment will have N no. of columns how can i fetch this N no. of columns.

    Very hard problem, because ref cursors do not (directly) support description!
    Se mine (non-ideal) solution (it may be doable, but it isn't very practical
    or easily maintainable):
    1. "Generic" package
    CREATE OR REPLACE PACKAGE dyn_fetch IS
    TYPE ref_cur_t IS REF CURSOR;
    g_query VARCHAR2 (32000);
    g_count NUMBER;
    g_desc_tab DBMS_SQL.DESC_TAB;
    varchar2_type CONSTANT PLS_INTEGER := 1;
    number_type CONSTANT PLS_INTEGER := 2;
    date_type CONSTANT PLS_INTEGER := 12;
    rowid_type CONSTANT PLS_INTEGER := 11;
    char_type CONSTANT PLS_INTEGER := 96;
    long_type CONSTANT PLS_INTEGER := 8;
    raw_type CONSTANT PLS_INTEGER := 23;
    mlslabel_type CONSTANT PLS_INTEGER := 106;
    clob_type CONSTANT PLS_INTEGER := 112;
    blob_type CONSTANT PLS_INTEGER := 113;
    bfile_type CONSTANT PLS_INTEGER := 114;
    PROCEDURE describe_columns;
    FUNCTION record_def RETURN VARCHAR2;
    END;
    CREATE OR REPLACE PACKAGE BODY dyn_fetch IS
    PROCEDURE describe_columns IS
    l_cur INTEGER;
    BEGIN
    l_cur := DBMS_SQL.OPEN_CURSOR;
    DBMS_SQL.PARSE (l_cur, g_query, DBMS_SQL.NATIVE);
    DBMS_SQL.DESCRIBE_COLUMNS (l_cur, g_count, g_desc_tab);
    DBMS_SQL.CLOSE_CURSOR (l_cur);
    EXCEPTION
    WHEN OTHERS THEN
    IF DBMS_SQL.IS_OPEN (l_cur) THEN
    DBMS_SQL.CLOSE_CURSOR (l_cur);
    END IF;
    RAISE;
    END;
    FUNCTION record_def RETURN VARCHAR2 IS
    l_record_def VARCHAR2 (32000);
    l_type VARCHAR2 (100);
    l_col_type PLS_INTEGER;
    l_col_max_len PLS_INTEGER;
    l_col_precision PLS_INTEGER;
    l_col_scale PLS_INTEGER;
    BEGIN
    FOR i IN 1..g_count LOOP
    l_col_type := g_desc_tab(i).col_type;
    l_col_max_len := g_desc_tab(i).col_max_len;
    l_col_precision := g_desc_tab(i).col_precision;
    l_col_scale := g_desc_tab(i).col_scale;
    IF l_col_type = varchar2_type THEN
    l_type := 'VARCHAR2(' || l_col_max_len || ')';
    ELSIF l_col_type = number_type THEN
    l_type := 'NUMBER(' || l_col_precision || ',' || l_col_scale || ')';
    ELSIF l_col_type = date_type THEN
    l_type := 'DATE';
    ELSIF l_col_type = rowid_type THEN
    l_type := 'ROWID';
    ELSIF l_col_type = char_type THEN
    l_type := 'CHAR(' || l_col_max_len || ')';
    -- ELSIF l_col_type = ...
    -- long_type, raw_type ...
    END IF;
    l_record_def := l_record_def || ' col_' || i || ' ' || l_type || ',';
    END LOOP;
    l_record_def := RTRIM (l_record_def, ',');
    RETURN l_record_def;
    END;
    END;
    Note that procedure "record_def" creates columns names as col_1 (col_2 ...)
    because SELECT clause in your query can be without aliases, for example
    "SELECT deptno || dname FROM dept".
    2. Your package which returns query nad ref cursor
    CREATE OR REPLACE PACKAGE test IS
    PROCEDURE set_query (p_query VARCHAR2 := NULL);
    FUNCTION ref_cur RETURN dyn_fetch.ref_cur_t;
    END;
    CREATE OR REPLACE PACKAGE BODY test IS
    PROCEDURE set_query (p_query VARCHAR2 := NULL) IS
    l_query VARCHAR2 (32000) :=
    ' SELECT e.empno, e.ename,' ||
    ' e.deptno, d.dname' ||
    ' FROM emp e,' ||
    ' dept d' ||
    ' WHERE e.deptno = d.deptno';
    BEGIN
    IF p_query IS NULL THEN
    dyn_fetch.g_query := l_query;
    ELSE
    dyn_fetch.g_query := p_query;
    END IF;
    END;
    FUNCTION ref_cur RETURN dyn_fetch.ref_cur_t IS
    l_ref_cur dyn_fetch.ref_cur_t;
    BEGIN
    OPEN l_ref_cur FOR dyn_fetch.g_query;
    RETURN l_ref_cur;
    END;
    END;
    Why we need two separate procedures (functions) in your package ?
    a) Receiving program must use dynamic SQL, but in dynamic block we can access
    only PL/SQL code elements that have global scope (standalone functions and procedures,
    and elements defined in the specification of a package).
    Unfortunately, cursor variables cannot be defined in the specification of a package
    (cannot be global variables).
    b) Receiving program must get the column list before ref cursor.
    So, we have two options: call (in receiving program) the same function two times
    (once to get the column list and once to return a ref cursor)
    or use one procedure (or function) for returning query (to get the column list)
    and second function for returning a ref cursor.
    3. Your receiving program
    CREATE OR REPLACE PROCEDURE test_fetch_ref_cur (p_query VARCHAR2 := NULL) IS
    l_statement VARCHAR2 (32000);
    FUNCTION process_def RETURN VARCHAR2 IS
    l_process_def VARCHAR2 (32000);
    BEGIN
    l_process_def := 'DBMS_OUTPUT.PUT_LINE (';
    FOR i IN 1 .. dyn_fetch.g_count LOOP
    l_process_def := l_process_def || ' l_record.col_' || i || ' || ''>>'' || ';
    END LOOP;
    l_process_def := RTRIM (l_process_def, ' || ''>>'' || ') || ');';
    RETURN l_process_def;
    END;
    BEGIN
    test.set_query (p_query);
    dyn_fetch.describe_columns;
    l_statement :=
    ' DECLARE' ||
    ' TYPE record_t IS RECORD (' ||
    dyn_fetch.record_def || ');' ||
    ' l_record record_t;' ||
    ' l_ref_cur dyn_fetch.ref_cur_t;' ||
    ' BEGIN' ||
    ' l_ref_cur := test.ref_cur;' ||
    ' LOOP' ||
    ' FETCH l_ref_cur INTO l_record;' ||
    ' EXIT WHEN l_ref_cur%NOTFOUND;' ||
    process_def ||
    ' END LOOP;' ||
    ' CLOSE l_ref_cur;' ||
    ' END;';
    EXECUTE IMMEDIATE l_statement;
    END;
    You can test this with:
    SET SERVEROUTPUT ON;
    EXECUTE test_fetch_ref_cur;
    Note that we can try to use more generic solution:
    CREATE OR REPLACE PACKAGE dyn_fetch IS
    -- SAME AS BEFORE, PLUS:
    PROCEDURE fetch_ref_cur (
    p_function_ref_cur VARCHAR2,
    p_process_def VARCHAR2);
    END;
    CREATE OR REPLACE PACKAGE BODY dyn_fetch IS
    -- SAME AS BEFORE, PLUS:
    PROCEDURE fetch_ref_cur (
    p_function_ref_cur VARCHAR2,
    p_process_def VARCHAR2)
    IS
    l_statement VARCHAR2 (32000);
    BEGIN
    l_statement :=
    ' DECLARE' ||
    ' TYPE record_t IS RECORD (' ||
    record_def || ');' ||
    ' l_record record_t;' ||
    ' l_ref_cur dyn_fetch.ref_cur_t;' ||
    ' BEGIN' ||
    ' l_ref_cur := ' ||
    p_function_ref_cur || ';' ||
    ' LOOP' ||
    ' FETCH l_ref_cur INTO l_record;' ||
    ' EXIT WHEN l_ref_cur%NOTFOUND;' ||
    p_process_def ||
    ' END LOOP;' ||
    ' CLOSE l_ref_cur;' ||
    ' END;';
    EXECUTE IMMEDIATE l_statement;
    END;
    END;
    CREATE OR REPLACE PROCEDURE test_fetch_ref_cur (p_query VARCHAR2 := NULL) IS
    FUNCTION process_def RETURN VARCHAR2 IS
    -- SAME AS BEFORE
    END;
    BEGIN
    test.set_query (p_query);
    dyn_fetch.describe_columns;
    dyn_fetch.fetch_ref_cur (
    p_function_ref_cur => 'test.ref_cur',
    p_process_def => process_def);
    END;
    Regards,
    Zlatko Sirotic

  • Dynamic sql and ref cursors URGENT!!

    Hi,
    I'm using a long to build a dynamic sql statement. This is limited by about 32k. This is too short for my statement.
    The query results in a ref cursor.
    Does anyone have an idea to create larger statement or to couple ref cursors, so I can execute the statement a couple of times and as an result I still have one ref cursor.
    Example:
    /* Determine if project is main project, then select all subprojects */
    for i in isMainProject loop
    if i.belongstoprojectno is null then
    for i in ProjectSubNumbers loop
    if ProjectSubNumbers%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    else
    for i in ProjectNumber loop
    if ProjectNumber%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    end if;
    end loop;
    /* Open ref cursor */
    open sql_output for SqlStatement;
    Thanks in advance,
    Jeroen Muis
    KCI Datasystems BV
    mailto:[email protected]

    Example for 'dynamic' ref cursor - dynamic WHERE
    (note that Reports need 'static' ref cursor type
    for building Report Layout):
    1. Stored package
    CREATE OR REPLACE PACKAGE report_dynamic IS
    TYPE type_ref_cur_sta IS REF CURSOR RETURN dept%ROWTYPE; -- for Report Layout only
    TYPE type_ref_cur_dyn IS REF CURSOR;
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn;
    END;
    CREATE OR REPLACE PACKAGE BODY report_dynamic IS
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn IS
    ref_cur_dyn type_ref_cur_dyn;
    BEGIN
    OPEN ref_cur_dyn FOR
    'SELECT * FROM dept WHERE ' | | NVL (p_where, '1 = 1');
    RETURN ref_cur_dyn;
    END;
    END;
    2. Query PL/SQL in Reports
    function QR_1RefCurQuery return report_dynamic.type_ref_cur_sta is
    begin
    return report_dynamic.func_dyn (:p_where);
    end;
    Regards
    Zlatko Sirotic
    null

  • Ref Cursors / throwing data into a Ref Cursor as data is fetched

    I was wondering if anyone has executed an SQL statement and as each row is being fetched back from an SQL, doing some data checks and processing to see if the row is valid to return or not, based on the values being fetched in an SQL.
    For example, I'm taking an SQL statement and trying to do some tuning. I have an Exists clause in the Where statement that has a nested sub-query with some parameters passed in. I am attempting to move that statement to a function call in a package (which is called in the SELECT statement). As I fetch each row back, I want to check some values that are Selected and if the values are met, then, I want to execute the function to see if the data exists. If it does exist, then, I want the fetched row returned in the Ref Cursor. If the criteria is met and the row doesn't exist in the function call, then, I don't want the fetched row to return.
    Right now, the data has to be thrown to REF Cursor because it's being outputted to the Java application as a Result Set.
    I've found many statements where you can take a SELECT statement and throw the Results in the Ref Cursor. But, I want to go a step further and before I throw each row in the Ref Cursor, I want to some processing to see if I put the Fetched Row in the Ref Cursor.
    If someone has a better idea to accomplish this, I'm all ears. Like I say, I'm doing this method only for the sake of doing some database tuning and I think this will speed things up. Having the EXISTS clause works and it runs fast from an End-user standpoint but, when it processes on the database with the nested subquery, it is slow.
    Here's an example of something that might be a problem (Notice the nested subquery). I moved the nested subquery to a function call written on the database package and make the call to the procedure/package in the SELECT statement. As I process each row, I want to check some values prior having the function call execute. If it meet some criteria, then the record is Ok to fetch and display in the Ref Cursor. If it does not meet the criteria and goes through the function and doesn't return data, then, I don't want the Fetched row from the main query to return the data.:
    SELECT EMPNO,
    FIRST_NAME,
    LAST_NAME
    FROM EMP E,
    DEPT D
    WHERE E.DEPTNO = D.DEPTNO
    AND EXISTS (SELECT 'X'
    FROM MANAGER M
    WHERE M.MANAGER_ID = E.MANAGER_ID
    AND MANAGER_TYPE IN (SELECT MANAGER_TYPE
    FROM MANAGER_LOOKUP ML WHERE ML.MANAGER_TYPE = M.MANAGER_TYPE))
    Any help or ideas of other things to try is appreciated. Keep in mind that I am returning this data to the Java application so, throwing the data to a Ref Cursor in the PL/SQL is the ideal method.
    Chris

    Ref cursors are not required nor desirable when writing java database application. Cursors are mentioned only once in the JDBC documentation reference guide, in the section "Memory Leaks and Running Out of Cursors".
    In a word cursors are just plain ridiculous, and in fact I never used them in my 15+ years of application development practice:
    http://vadimtropashko.wordpress.com/cursors/

Maybe you are looking for

  • File adapter content conversion

    Hi all,   We are having File to File Scenario   We are facing problem in Content conversion in File   Adapter(Sender)   The source file is in text format and fields are   seperated by '|' character   The source file structure is :   Header|No. of Rec

  • Urls in a HTML document

    What are the advantages of making an url relative to Site Root? Why some people making the url in this way, although relative to document much simpler is? thanks

  • HP pavilion Dv6 Fan Problem - Want to know replacement part number

    Hi, I purchased HP Pavilion dv6t QE in Dec 2011. Just after the warranty expired in Dec 2012 its fan stopped working. Whenever I am starting laptop I am getting error that laptop fan is not working correctly. I am ready to get the fan/heat sink chang

  • Photosmart D7560 prints alignment page too often.

    The D7560 is installed on my iMac. I bought the printer 2 years ago and it's been very frustrating. It runs out of black ink after a dozen pages or less. And it keeps wanting to do an alignment. That could be how my cartridge is getting wasted. Does

  • Modified an EDI 940 process, GS01 does not fill with OW in fact is blank. Causes issues with the partner.

    I consolidated a 940 process that was sendind flat file/edi/xml/sql server to run all from one orchestration and dynamic send ports (some are send to the file system and some to ftp). Before everything was working perfect, with the changes everything