PL/SQL rows in a cursor

How do I check the number of rows in a CURSOR without a complete fetch,If the records exist it should return a REF cursor else it shouls say no records.
How can this be done

%rowcount returns the number of rows fetched, not the number of rows returned by the query
  1  DECLARE
  2    CURSOR x IS SELECT ename FROM emp;
  3    l_ename emp.ename%type;
  4  BEGIN
  5    OPEN x;
  6    FETCH x INTO l_ename;
  7    WHILE x%found
  8    LOOP
  9      dbms_output.put_line( x%rowcount );
10      FETCH x INTO l_ename;
11    END LOOP;
12* END;
SCOTT @ HP92 Local> /
1
2
3
4
5
6
7
8
9
10
11
12
13
14
PL/SQL procedure successfully completed.Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC

Similar Messages

  • Get the number of rows in a cursor?

    Currently I have a pretty simple stored procedure that builds some dynamic SQL then returns those results to some code.
    I would like also to be able to return the number of rows in that cursor back to the Java code, how can I do this? Some sample SQL is shown below:
    l_query := 'Select * from customer';
    OPEN searchResults FOR l_query;
    ???? Select count(*) into totalResults from searchResults; ????
    (^^This last row is the issue)
    I need to return the varaible totalResults as the count
    Thanks heaps!!

    Mark,
    If I understand you correctly, what you desire cannot be done.
    When Oracle opens a cursor, it doesn't know how many rows that cursor will return.
    The only two options is either do a separate query to count the number of rows that the original query will return, or fetch all the rows and see how many you got.
    I recall seeing an example of that in the JDBC sample code on the OTN Web site.
    (But I'm too lazy to look for it for you.)
    Good Luck,
    Avi.

  • How to type cast PL/SQL table to REF cursor?

    any one knows how to CAST PL/SQl table to Ref cursor?
    eg
    procedure some_name(r_out out sys_refcurosr)
    IS
    type t is table of tab%ROWTYPE;
    my_type t;
    begin
    select * bulk collect into my_type from tab;
    r_out := my_type; -- need help here..
    end;
    it's 10g

    ref cursor is pointer to result set. You can not cast to PL/SQL table.
    1 create or replace procedure some_name(r_out out sys_refcursor)
    2 IS
    3 begin
    4 OPEN r_out for select * from emp;
    5* end;
    SQL> /
    Procedure created.
    SQL> var mycursor refcursor;
    SQL> exec some_name(:mycursor);
    PL/SQL procedure successfully completed.
    SQL> set linesize 2000
    SQL> print :mycursor;
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7369 SMITH CLERK 7902 12/17/80 00:00:00 800 20
    7499 ALLEN SALESMAN 7698 02/20/81 00:00:00 1600 300 30
    7521 WARD SALESMAN 7698 02/22/81 00:00:00 1250 500 30
    7566 JONES MANAGER 7839 04/02/81 00:00:00 2975 20
    7654 MARTIN SALESMAN 7698 09/28/81 00:00:00 1250 1400 30
    7698 BLAKE MANAGER 7839 05/01/81 00:00:00 2850 30
    7782 CLARK MANAGER 7839 06/09/81 00:00:00 2450 10
    7788 SCOTT ANALYST 7566 04/19/87 00:00:00 3000 20
    7839 KING PRESIDENT 11/17/81 00:00:00 5000 10
    7844 TURNER SALESMAN 7698 09/08/81 00:00:00 1500 0 30
    7876 ADAMS CLERK 7788 05/23/87 00:00:00 1100 20
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7900 JAMES CLERK 7698 12/03/81 00:00:00 950 30
    7902 FORD ANALYST 7566 12/03/81 00:00:00 3000 20
    7934 MILLER CLERK 7782 01/23/82 00:00:00 1300 10
    14 rows selected.

  • Count of rows in a cursor

    please help me with the function to count the number of rows in a cursor.

    You can use %ROWCOUNT attribute as follows:
    DECLARE
         CURSOR C IS
              SELECT 1 FROM DUAL;
    BEGIN
         FOR R IN C LOOP
              DBMS_OUTPUT.Put_Line('%ROWCOUNT = ' || C%ROWCOUNT);
         END LOOP;
    END;
    but if you want to have number of rows in a cursor BEFORE you fetch any rows from it - then sorry, no way. You can't have number of rows before you physically count them, i.e. read them from the disk in the first place. Think of tables with billions of rows...
    file:///D:/Oracle10g_Docs/B12037_01/appdev.101/b10807/06_ora.htm#sthref800

  • Sql exception : maximum open cursors exceeded

    I run applicatio to insert data into the table, and update data into the table, when it processes more than 800 record, it throws the sql exception :maximum open cursors exceeded.
    Who knows the reason?
    Thanks.

    I have a similar problem where in I close the Result set, Statement and close the connection in a finally block. Even though, the connection.close() executes sucessfully, with no exceptions being thrown, I still see the connection opened in ORacle. This builds up connections for our application and by the end of the day we are up with about 500 connections open and rising.
    After closing the connection, I did check the value for connection.isClosed() and it still says false (like before the connection was closed). Since we are using a custom Connection manager to pool the connections, my interpretation is that even after the connection is closed, it doesn't get released. I have tried setting the connection to Null, used the finalize method to still check for connection != null and do one more close(), but still the connection is still open.
    Am I mistaken in my thinking that even though the connection seems to be closed(), it doesn't get released until the GC runs and picks it for disposal? For every job, after the process is completed we have about 7 open connections and at times the number stays at 7 for some more jobs (Web application driven by servlets and some rmi in the background process). I thne see a surge in the connection after some more jobs are processed and so am not sure whether its the connection manager to blame. Could any one have any pointers on this issue.
    Thanks for your response.

  • How to count number of rows in a cursor???

    I have a cursor and i want to check number of row fetched...But not through rowcount... bcoz it will give after fetching all the rows..
    I want to get count as soon as i open the cursor..plz let me know

    David_Aldridge wrote:
    hmmm ... you'd have to wrap the query in an inline view and apply the count(*) over() in the main query I guess.Still will not cover all cases:
    Session 1:
    update emp set deptno = deptno where deptno = 20
    5 rows updated.
    SQL> Session 2:
    select  ename,
            count(*) over()
      from  emp
      for update
      skip locked
    ENAME      COUNT(*)OVER()
    ALLEN                  14
    WARD                   14
    MARTIN                 14
    BLAKE                  14
    CLARK                  14
    KING                   14
    TURNER                 14
    JAMES                  14
    MILLER                 14
    9 rows selected.Now try to wrap the above query in an inline view :).
    SY.

  • How to get SQL text from dbms_sql cursor ID

    Hello,
    I have a progam using dbms_sql. A cursor is built by dbms_sql.parse (cur_id, v_query, dbms_sql.native);From now on I have only the internal ID cur_id of the cursor. Is there a way to get back the original query the cursor is built from when the cursor is passed to another package?
    Regards
    Marcus

    Oracle provides several views that show part or all of the SQL statement. See your Oracle version# Reference manual for v$sql...
    v$sqltext is one view that displays the full text but the text is contained in multiple rows.
    HTH -- Mark D Powell --

  • 26.4 Basing an entity Object on a PL/SQL Package API - Ref Cursor, no View

    I am hoping that I could get some help in the details of a problem. I am trying to follow the directions in the Oracle Application Development Framework Developer's Guide for Forms/4GL Developers, Section 26.4 - Basing an Entity Object on a PL/SQL Package API.
    There is example code in the downloadable AdvancedEntityExamples - EntityWrappingPL/SQLPackage
    The question is, how will the implementation change if the entity is based entirely on PL/SQL - simply stated - no view is available, just ref cursors and insert,update,delete procedures.
    In the example code, there are two procedures, lock_product and select_product. This is where things get more complicated. I can create a function to return a single record ref cursor, instead of the list of OUT variables defined in both functions (select_product and lock_product). It makes sense that I just return one cursor and get all of the columns from that instead of lots of OUT variables.
    So what's stopping me you may ask... There is one difference between select_product and select_lock. Select_lock has a select that includes "FOR UPDATE NOWAIT". I don't have that as an option when creating my ref cursor. I am not sure what the impact of "FOR UPDATE NOWAIT" is? Can I ignore it?
    In the problem I am working with, (getting data from Oracle Portal 10.1.4) I return the following:
    function getRefCursor return ref_cursor is
    v_tab wwsbr_all_items_object_type := wwsbr_all_items_object_type();
    p_recordset wwsbr_types.cursor_type;
    l_results wwsrc_api.items_result_array_type;
    begin
    wwctx_api.set_context(<username>,<password>);
    l_results := wwsrc_api.item_search(.. parameters..);
    <snip>
    ... Loop through the objects and populate v_tab
    <snip>
    open p_recordset for
    select * from table(cast(v_tab as wwsbr_all_items_object_type));
    return p_recordset;
    end getRefCursor;
    With this sample, it would be easy to return a single row by passing the masterid as a parameter.
    So I am still left with, how should the implementation of callLockProcedureAndCheckForRowInconsistency() and callSelectProcedure() be changed in order to use a ref cursor instead of a view? The user guide was missing that extra section <bg>.
    What would be REALLY helpful, is an example, say 26.4A that demonstrates creating an entity object from a ref cursor and procedures from PL/SQL only without a view.
    Thank you, Ken

    The lock procedure is expected to obtain a row-level lock on the row, given its key.
    Depending on the setting of jbo.locking.mode, the entity object's lock() method will be invoked either as soon as the first persistent attribute is successfully modified by the user (in the case of jbo.locking.mode=pessimistic), or it will be called during commit processing just before the row is updated in the database (with jbo.locking.mode=optimistic).
    Usually 2-tier Swing applications use pessimistic mode, while web applications use optimistic mode.
    The FOR UPDATE NOWAIT is the Oracle clause that can be appened to a SELECT statement to acquire a row-level lock on the selected rows. The NOWAIT modifier means that rather than hanging, waiting for a row locked by another user to free up, it will raise an exception if any of the rows being selected-and-locked are not available to lock.
    If you're not able to work the FOR UPDATE NOWAIT into the syntax of the ref cursor, perhaps you can initially perform the lock using a different cursor inside the stored procedure, then return your ref cursor.

  • PL/SQL dynamic insert using cursor

    Hello all,
    I'm having big performance issues with (as you'll see below, a very simple) stored procedure. Any hints/suggestions would be really appreciated. Query below in the Loop is used to create a list of all months that fall within a member's start_date & end_date for insertion to member_months table. Can anyone suggest maybe a different approach to improve run time? It was timing out just using SQL, thought I might try PL. Thanks for anyone's help.
    CREATE OR REPLACE PROCEDURE proc_MEMBER_MONTHS authid current_user as
    /* get all Master member id's for cursor */
    CURSOR c_unique_mmi IS
        select distinct master_member_id
        from member;
    v_mmi                           member.master_member_id%TYPE;
    BEGIN
    dbms_output.enable(null);
       OPEN c_unique_mmi;
        LOOP
            FETCH c_unique_mmi INTO v_mmi;   /* pass mmi in cursor to variable */
            EXIT WHEN c_unique_mmi%NOTFOUND;
      INSERT INTO member_months   
          (mmi,                                        
          member_nbr,
          lob,
          member_month,
          member_year,
          member_month_count)
    (SELECT master_member_id mmi,
            member_nbr,
            lob,
            month member_month,
            year member_year,
            ROW_NUMBER ()
              OVER (PARTITION BY member_nbr ORDER BY lob, year, month ASC)
              member_month_count
      FROM (SELECT DISTINCT
                       master_member_id,
                       member_nbr,
                       lob,
                       TO_CHAR (ADD_MONTHS (eligibility_start_date, LEVEL - 1), 'MM')
                          as MONTH,
                       TO_CHAR (ADD_MONTHS (eligibility_start_date, LEVEL - 1),
                                'YYYY')
                          as YEAR
                  FROM (SELECT *
                          FROM mmi_data
                         WHERE master_member_id = v_mmi)              /* v_mmi is current MMI variable passed from cursor */
            CONNECT BY LEVEL <=
                            MONTHS_BETWEEN (TRUNC (eligibility_end_date, 'MM'),
                                            TRUNC (eligibility_start_date, 'MM'))
                          + 1));
        commit;
        END LOOP;
        CLOSE c_unique_mmi;
    END;
    /Edited by: BluShadow on 08-Aug-2012 14:03
    added {noformat}{noformat} tags for readability.  Please read {message:id=9360002} and learn to do this yourself.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    All you would need is a direct insert like this
         insert into member_months   
                mmi
              , member_nbr
              , lob
              , member_month
              , member_year
              , member_month_count
          select   master_member_id mmi
              , member_nbr
              , lob
              , member_month
              , member_year
              , row_number () over (partition by member_nbr order by lob, year, month asc) member_month_count
            from (
                select distinct master_member_id
                    , member_nbr
                    , lob
                    , to_char (add_months (eligibility_start_date, level - 1), 'mm') as member_month
                    , to_char (add_months (eligibility_start_date, level - 1), 'yyyy') as member_year
                  from (
                      select *
                        from mmi_data
                        join (
                            select distinct master_member_id v_mmi
                              from member
                          on master_member_id = v_mmi
               connect
                    by level <= months_between (trunc (eligibility_end_date, 'mm'), trunc (eligibility_start_date, 'mm'))+ 1
              );Your procedure should have only this nothing else. Drop the cursor and looping.
    If you want help in tuning the above query please give us the following details.
    1. DB Version.
    2. Execution Plan
    3. Table Details (Number of rows)
    4. Index Details

  • Why do we need varrays ,index by table,pl/sql table etc when cursor is avai

    hi,
    Why do we need Composite data types like Index by Table, varrays etc when we have cursors and we can do all the things with cursor.
    Thanks
    Ram

    I would have to create a collection type for each column in the select statement.No.
    SQL> select count(*) from scott.emp ;
      COUNT(*)
            14
    1 row selected.
    SQL> DECLARE
      2      TYPE my_Table IS TABLE OF scott.emp%ROWTYPE;
      3      my_tbl my_Table;
      4  BEGIN
      5      SELECT * BULK COLLECT INTO my_tbl FROM scott.emp;
      6      dbms_output.put_line('Bulk Collect rows:'||my_tbl.COUNT) ;
      7  END;
      8  /
    Bulk Collect rows:14
    PL/SQL procedure successfully completed.
    SQL> disc
    Disconnected from Oracle9i Enterprise Edition Release 9.2.0.7.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.7.0 - Production
    SQL>Message was edited by:
    Kamal Kishore

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

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

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

  • How to know the number of rows in a cursor?

    Hi all,
    How can i know how many rows a cursor has ?
    Glen

    dbms_sql... you can use when you want to know how many lines of code the cursor has.
    If you want to know how many rows it will fetch, you have to fetch all rows - the number of rows actually fetched are assigned to the variable <cursor_name>%ROWCOUNT.
    When you don´t want to fetch all rows, all you can do is count(*)...
    Regards,
    Gerd

  • Index of the row where the cursor is clicked

    Hi all,
       I need to set some values in table control for the fields where i clicked the cursor.  Actually i am using the below code but its not working... 
         lo_el_zdcapsc = wdevent->get_context_element( 'CONTEXT_ELEMENT'  ).
        lv_sel_index = lo_el_zdcapsc->get_index( ).
             lo_nd_zdcapsc->set_attribute(
           EXPORTING
             index = lv_sel_index
             name =  `ZPLANTID`
             value = lv_plant ).
    For example I placed the cursor in 3 row at the plant column in my table control. So only 3 row plant value has to be set.
    Can anybody tell me how to read the index when a cursor is placed at a particular row.
    Regards
    Sireesha.

    hi
    u can use get_index method to get the index of the particular row selected
    data: lr_element type ref to if_wd_context_element.
    DATA ls_cn_node TYPE wd_this->element_cn_node.
    lr_element = wdevent->get_context_element( 'CONTEXT_ELEMENT' ).
    * get all declared attributes
      lr_element->get_static_attributes(
        IMPORTING
          static_attributes = ls_cn_node ).
    data lv type I.
    lv = lr_element->GET_INDEX( ).
    u have got the table row values in a strucure , now u can set it to new value
    regards,
    amit

  • How to manipulate data in multiple rows without using cursor??

    Hi all,
    I have a form in which there is a push button & 4 text fields.
    Push button : Process
    Text fields: Year, Month, Financial_To_Year, Financial_From_Date.
    In database , there are tables like, CUSTOMER_MASTER, FD_ACCOUNT_MASTER, FD_ACCOUNT_DTL, CUSTOMER_YEARLY_INTEREST, etc.
    In table FD_ACCOUNT_MASTER, there are columns, like CUST_CODE, FD_ACCT_NO, FD_AMOUNT, ACCT_OPEN_DT, ACCT_CLOSE_DATE, ACCT_TYPE, INTEREST_RATE, etc.
    There are thousands of records in the table.
    For Push button : Process , TRIGGER: When button pressed,
    I have to do all the process of FD for all the FD_ACCOUNTS at once. Process means i have to calculate Interest for all the accounts, calculate interest monthly, quarterly, yearly and make the FD_Accounts disable after the date of ACCT_CLOSE_DATE is reached, make the accounts renewed , etc all the process.
    But to do this process for multiple rows at once, we use cursor, but i don't want to use cursor as i feel its too tedious to do.
    Is there any other way , where i do process of multiple records at once without using cursor??
    Help me, Thank You.
    Oracle Forms Builder 6i.
    Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production

    An Update statement certainly can update sets of data instead single row updates:
    UPDATE Statement
    if you can't do it in a single statement you can use bulk processing as well:
    PLSQL 101
    cheers

  • Creating Web services using JDeveloper for Pl/SQL package having ref cursor

    Hi,
    I am trying to create web services for PL/SQL package in JDeveloper. When I am trying to create this web service, the functions in the package which is returning referential cursor or record cursor are not visible. When I highlight the function and click "Why Not?", it displays the message "The following types used by the program unit do not have an XML schema mapping and/or serializer Specified: REF CURSOR". Could you please let me know, how I can create this web service?
    I am getting similar error when I am trying to create web service for a package with overloaded functions also.
    Thanks,

    Ok so I played around with this some more. I created the same process in bpel using oracle bpel designer and here are the results.
    1. Against 10g database running a synch process data is retutned without error.
    2. Against 9i database running an asynch process data is retutned without error.
    3. Against 9i database running a synch process data is retutned with error.
    I'm definilty missing something.

Maybe you are looking for

  • AP Power difference between WEP and WPA

    Can someone tell me what to look for? I have two SSIDs on an AP: one is WEP and the other is WPA. I have 5 bars on WEP ssid, but only 2 on the WPA side and eventually down to one. Thanks, John

  • Firefox does not quit automatically after logging out of my computer

    Hey, everyone. Just curious if anyone has experienced a similar problem as me. I am working on a G5, running Mac OS X (10.4.8) using the newest verson of Firefox 1.5.07. Intermittently, I cannot log out of my computer without first closing Firefox. S

  • Parsing Eroor when opening chat support

    Hello all, I am trying to figure out what is wrong with a chat support link on a website that I frequent, but I am not an XML guru, and need some advise please.... When you click on the link, a window used to ope that prompted a chat session, but now

  • Video playlists show up in music playlists!

    I originally had the problem where my music playlists were showing up in my video playlists section of the ipod along with my 2 video playlists (movies and tv shows). I have finally solved THAT issue by putting 'tv shows' or 'movies' in the comments

  • Lsmw with help of bapi

    Hi All i am doing LSMW with help of BAPI for transaction mm01. Initially i used the bapi name "bapi_standardmaterial_create" but it do not allow me for any method like create, edit etc. then i used the bapi name "bapi_material_savedata" but i do not