Counting rows in a loop

Hi,
I am trying to learn pl/sql and I need some help, please.
I have written a package with a cursor and a loop, which returns a file with some lines.
The last step I have to do is to write something that returns the number of lines produced in the file: i.e, if the loop retuns 356 lines, I have to write something that calculates that figure and returns the result in the last line.
I was told that I need to create a variable and place it somewhere at this point to do the calculation:
END LOOP;
Utl_File.Put(l_Output, 'end of file');
Utl_File.Fclose(l_Output);
I do not quite understand what to do or how to do it, can someone help?
Thanks

<s></s>
DECLARE
   CURSOR your_loop
   IS
      SELECT *
        FROM scott.emp;
   your_counts   INTEGER;
BEGIN
   FOR c IN your_loop
   LOOP
      your_counts := your_loop%ROWCOUNT;
      DBMS_OUTPUT.put_line(to_char(your_counts,'999')||':'||c.ename);
   END LOOP;
   DBMS_OUTPUT.put_line(to_char(your_counts,'999')||' lines written');
END;
1:SMITH
2:ALLEN
3:WARD
4:JONES
5:MARTIN
6:BLAKE
7:CLARK
8:KING
9:TURNER
10:JAMES
11:FORD
12:MILLER
12 lines written
PL/SQL procedure successfully completed.
DECLARE
   CURSOR your_loop
   IS
      SELECT *
        FROM scott.emp;
   your_counts   INTEGER;
BEGIN
   your_counts := 0;
   FOR c IN your_loop
   LOOP
      your_counts := your_counts + 1;
      DBMS_OUTPUT.put_line(to_char(your_counts,'999')||':'||c.ename);
   END LOOP;
   DBMS_OUTPUT.put_line(to_char(your_counts,'999')||' lines written');
END;
1:SMITH
2:ALLEN
3:WARD
4:JONES
5:MARTIN
6:BLAKE
7:CLARK
8:KING
9:TURNER
10:JAMES
11:FORD
12:MILLER
12 lines written
PL/SQL procedure successfully completed.

Similar Messages

  • Count rows from multiple tables using SQL only

    Hi, I know this has probably been answered before, but I couldn't find the answer anywhere. Please help.
    I'd like count(*) [rows] for all tables in database using SQL only - no PL/SQL
    The result should be something like:
    Table RowCount
    DBA_TABLES 1000
    DBA_USERS 50
    etc.
    Thanks!

    offcource write this script:
    create or replace procedure count_tables (ip_schema VARCHAR2)
    is
    lv_owner VARCHAR2(100);
    lv_table_name VARCHAR2(100);
    lv_sql_statement VARCHAR2(2000);
    lv_count_table NUMBER;
    CURSOR c1 IS
    SELECT owner, table_name
    FROM all_tables
    WHERE owner = ip_schema
    ORDER BY table_name;
    begin
    dbms_output.put_line ('+--------------------------------------------------------------------+');
    dbms_output.put_line ('¦ | | ¦');
    dbms_output.put_line ('¦ Schema Name | Table Name | Number of Rows ¦');
    dbms_output.put_line ('¦ | | ¦');
    dbms_output.put_line ('¦------------------------------------------------------------------¦');
    OPEN c1;
    LOOP
    FETCH c1 INTO lv_owner , lv_table_name;
    EXIT WHEN c1%NOTFOUND;
    lv_sql_statement := 'SELECT count(*) FROM ' || lv_owner || '.' || lv_table_name;
    EXECUTE IMMEDIATE lv_sql_statement INTO lv_count_table;
    IF lv_count_table > 0 THEN
    dbms_output.put_line ('| '||rpad(lv_owner, 14, ' ')||'| '|| rpad(lv_table_name, 32, ' ')||'| '|| rpad(lv_count_table, 16, ' ')||' |');
    -- dbms_output.put_line ('|---------------|---------------------------------|------------------|');
    END IF;
    END LOOP;
    CLOSE c1;
    dbms_output.put_line ('+--------------------------------------------------------------------+');
    exception
    WHEN OTHERS THEN
    dbms_output.put_line ('owner: '||lv_owner||' - table: '||lv_table_name||' - '||sqlerrm);
    end count_tables;
    set serveroutput on size 1000000
    exec count_tables
    drop procedure count_tables;

  • Can i count row from ResultSet ?

    I would like to count row from ResultSet for
    take it into my array object because i must know number of row before create array object.
    Example:
    ResultSet rset = stmt.executeQuery("select * from user ");
    /*i = amount of ResultSet*/
    User[] user = new User;
    int l=0;
    while (rset.next()){
    user[l] = new User();
    user.name = rset.getString(1);
    l++;

    Hi,
    As per my knowledge there is no method by which you can get the count of items in a resultset directly. You will have to loop through the reseltset and set a variable for count. In your specific case I would advise you to use a Vetor instead of an array so that you need not bother about the size.
    ResultSet rset = stmt.executeQuery("select * from user ");
    Vector user = new Vector();
    while (rset.next()){
    user.addElement(rset.getString(1));
    Now you will have a Vector that holds the user info. To retrieve the user info loop through the Vector.
    for (int i; i<user.size(); i++){
    userName = user.elementAt(i);
    Hope I was of some help.
    cheers!!!
    Nish

  • What is the problem with native dynamic sql when counting rows in all table

    what is the problem with native dynamic sql when counting rows in all table?Giving an error "table or view does not exist". Thanks.
    DECLARE
    v_sql_string varchar2(1000);
    v_no_of_rows number;
    BEGIN
    for i in ( select table_name from all_tables )
    loop
    v_sql_string := ' select count(1) from ' || i.table_name;
    dbms_output.put_line( v_sql_string );
    --execute immediate v_sql_string into v_no_of_rows;
    end loop;
    END;

    Usually your problem can be described with 'Who cares'. I mean, for what reason do you do this? I doubt that there's a business need to get 100 % accurate answers for this. Normally such things are used to get a picture about the growth of data.
    Personally I would prefer to have up-to-date statistics for all tables and just query the number of rows from there. Sufficient for me in < 99 % of all cases.
    Just my $ .02...

  • Count rows from several tables

    hello,
    im trying to count row from multiple tables
    for example i need the select statement to produce the following
    table_name count
    table1 5
    table2 6
    table3 3
    i came up with the following script but it counts the number of tables i have
    select object_name, (select count(*) from user_tables where table_name = object_name) from all_objects
    where object_type = 'TABLE'

    Manik wrote:
    May be possible:
    Check this:
    SELECT table_name,
    TO_NUMBER (
    EXTRACTVALUE (
    xmltype (
    DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
    '/ROWSET/ROW/C'))
    COUNT
    FROM (select * from all_tables where table_name in ('TABLE1','TABLE2'))
    WHERE owner = 'SCOTT';Cheers,
    Manik.Awesome Manik... Just too good. Thanks.
    I wish i could have given you the 'Correct' points. ;-)
    Can you please explain the logic in brief? Will be helpful for everybody to understand...

  • SQL Developer 2.1 EA - count rows with filter on a table

    This is a small problem that I came across today while using 2.1 EA. I opened a table and did a filter to narrow down the results of the table. Then when I right clicked on the search results and clicked on 'Count Rows'....I get the count of the rows in the table and not my search results.
    Is this a feature or a bug?
    Thanks,
    Mike

    In EA2, we get both the total and the filtered total, nice.
    Only remark is we don't get a progress indicator anymore, and thus can't cancel a query that might take up hours to finish!
    Please log a bug for this.
    Thanks,
    K.

  • Count rows in an internal table

    Anybody how knows how I can count rows in my internal table?

    Hi,
    Data: lines like sy-tabix.
    DESCRIBE TABLE ITAB LINES LINES.
    where itab is your internal table.
    This will work out.
    Please award sutiable points .
    Regards,
    Irfan

  • How to maintain counter in a for loop

    Hi, 
      How do we track counter in a loop?Isn't it the way I implemented.? Please suggest.
    Regards.
    Solved!
    Go to Solution.
    Attachments:
    for loop counter.jpg ‏219 KB

    Both loops have errors, if you try to do for(i=60;i<120;i++) you're only running 60 loops, not 120.
    You should also disable the autoindexing on incoming arrays as you want some split array indexes (actually you can optimize it by extracting the constant a[30] before the 1st loop and the opposite on the 2nd. Now you're extracting 2 numbers from a 1D array instead of 1 from a 2D array ...
    The number on the select/sum function should be integers, no need to calculate doubles.
    The small array to sum it up is only max 170 numbers, it's ok although a sum in a shift register would be better.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • How to set Tile count column or count row?

    How to set Tile count column or count row? If not can do, How
    to adjust count row or count column?
    Thx for all idea.

    The Tile container's number of columns and rows is calculated
    based on each child's width and height (or based on tileWidth and
    tileHeight which you can set). If you need more control over the
    layout, use Grid.

  • Count rows that are max timestamp

    Hi,
    I'm trying to run a query that will count only rows that are max timestamp.
    i have a submit table which has dates of submissions, however some application numbers have multiple rows in this table. I need to count only one row per application and it has to be the latest submission data.
    I have tried a subquery and its not working, I'm stuck at this point.
    Thanks for help :)
    example table
    pk app # submit_date
    12 test-1 02222011 13:30
    13 test-2 02232011 09:45
    14 test-1 02232011 09:51
    how do i count rows but based on max timestamp?

    select
    count(s.pk)
    from
    submit s
    where exists (select s1.app#, max(s1.submit_date) from submit s1 group by s1.app#)
    I dont really understand what you are doing there.
    SQL> WITH T
      2       AS (SELECT 12 pk, 'TEST-1' app#, SYSDATE submit_date FROM DUAL
      3           UNION ALL
      4           SELECT 13 pk, 'TEST-2' app#, SYSDATE + 1 submit_date FROM DUAL
      5           UNION ALL
      6           SELECT 14 pk, 'TEST-1' app#, SYSDATE + 2 submit_date FROM DUAL)
      7  SELECT * FROM T;
            PK APP#   SUBMIT_DA
            12 TEST-1 23-FEB-11
            13 TEST-2 24-FEB-11
            14 TEST-1 25-FEB-11
    SQL> WITH T
      2       AS (SELECT 12 pk, 'TEST-1' app#, SYSDATE submit_date FROM DUAL
      3           UNION ALL
      4           SELECT 13 pk, 'TEST-2' app#, SYSDATE + 1 submit_date FROM DUAL
      5           UNION ALL
      6           SELECT 14 pk, 'TEST-1' app#, SYSDATE + 2 submit_date FROM DUAL)
      7  SELECT   pk, app#
      8    FROM   (SELECT pk, app#, ROW_NUMBER () OVER (PARTITION BY app# ORDER BY submit_date DESC) rn
    FROM T)
      9   WHERE   rn = 1;
            PK APP#
            14 TEST-1
            13 TEST-2
    SQL>

  • Timed counter in a while loop without overlapping a second while loop

    Hello,
    Like you can see in attached file (waveform_counter.vi), I have a main while loop which makes a waveform graph and I would like to integer an inversed counter (from x seconds to 0) in some cases. I tried with a overlapped while loop, but obviously, when the counter works, the main loop breaks...
    How can I make a sort of time counter without a loop ? I tried with the while loop iteration, every 100 iterations the counter decreases but I don't success.
    Thanks for help.
    Nathalie.
    Attachments:
    waveform_counter.zip ‏55 KB

    Hello Nathalie:
    Please see what I did in the expiration case.
    Please advice if this is a possible solution.
    Attachments:
    waveform_graph 2.zip ‏41 KB

  • Counting Rows in a message in BPM

    Hi Experts, i need some knowledge sharing here.
    Anybody can tell me how can we get the numbers of rows in a message by using loop in BPM?
    I was thinking of using Loop and container node. But i still don't get it how can i use the loop condition so that my loop is not looping forever.
    Thank you so much guys....

    "I use the "Count" function in graphical message mapping and count the segments and add these to an unused field in the footer"
    Hi thx for the reply, however, can you explain to me in more detail.
    My scenario is i got a message with structure like this:
    Source Message:
    Header  1..1
        item  1..N
          Type 1..1
    Target Message:L
    Header 1..1
       result 1..1
    Now, i want to count how many are there Type with value is for example 'E' and map it to the target message in node 'result'.  So if there are 2 'Type' with value 'E' therefore the 'result' will filled with number '2'. If there is only 1 'Type' with value 'E' thus the 'result' will be filled with number '1'.
    Do I have to use oneAsMany function?

  • Counting rows in a ResultSet, help please?

    sorry there was a type error
    how to count the number of rows in a resultser object which may contains millions of rows? besides using a while loop? thanks

    You can do rs.last() then get the number of rows using rs.getRow() but as the previous poster hinted at this will take very long time with a lot of records as they all have to be retrieved before the rs.last() method can complete.

  • Counting rows in a mysql query

    Hey
    How do i count the rows in a mysql query?
    I have tried to make a while loop (as you can see in the code), but if i make this while loop i cant use the same query to get the database data.
    Doesnt java have a function that counts the rows?
    public DefaultTableModel searchCategory(String searchString){
            String returnString = "";
            try{
                RS = connection.executeQuery("SELECT name, price, products_type_id FROM katrinelund_products WHERE products_type_id = (SELECT products_type_id FROM katrinelund_products_type WHERE name LIKE '%"+searchString+"%')");
                int rowCount = 0;
                while(RS.next()){
                    rowCount++;
                String[] columnNames = {"Navn", "Pris", "Produkt type"};
                Object[][] data = new Object[rowCount][columnNames.length];
                int i=0;
                while(RS.next()){
                    data[0] = RS.getString(1);
    data[i][1] = RS.getString(2);
    data[i][2] = RS.getString(3);
    i++;
    table = new DefaultTableModel(data, columnNames);
    catch(SQLException E){
    System.out.println("Der skete en fejl" + E.getMessage());
    return table;
    }NOTE: the connection to the database is stored in the connection variable.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    yawmark wrote:
    The SELECT COUNT(*) cannot be fetched among other data, so in this case you must send two queries. Then there is much simplier to use the method I mentioned above.While it may be "simpler", it's not supported in a non-trivial number of drivers. So there are a number of situations in which your "simple" solution will not work. I assume you've been fortunate enough to work only with drivers that do support the functionality you recommend, but I can also only assume that you haven't had much experience beyond that.I apologize for my spelling errors. I'm not a native englishman.
    yawmark wrote:
    Knowing the amount of rows a resultset returns can be interesting if you're making some kind of search engine. Knowing the amount of data returned for a particular query can certainly be useful, and we've presented some reasonable means of obtaining that kind of information that don't rely on potentially unsupported features.
    I don't now about unsupported features. The ResultSet is (as far as I know) not tied to a specific SQL database. This, and all of it's methods is in the java.sql.ResultSet interface. Then all classes implementing this must have these methods. Am I not right?
    yawmark wrote:
    Stop dealing with however it's necessary or not.Sorry, partner, but you don't get to decide what I post here.
    This guy wants this problem to be solved, so apparentley he has a usage for it...And what you're apparently failing notice is that there are other solutions (better, in many cases) than the solution which you posted. Don't make the mistake of thinking your suggestion is golden. It isn't. Besides, there are no shortage of beginners that want the "problem" of i = i++ to be "solved"; no doubt they think they have an apparent usage for it, too. ~I'm well aware of that you decide on your own what to post. I just don't see how it is necessary to discuss the matter of necessity in this case. The problem still remains.
    I don't want any fuss here. I'm just so sick of everyone who yells "you don't need to know that". I haven't decried any of the other solutions (at least it wasn't my point), all I said was that it's not a good idea to send multiple queries to the database when you already have the answer three rows of code away. In some rare situations, the data may have been changed during the short period of time as the database is finished with the first query before you send the next one.

  • COUNT ROWS - Help

    My procedure takes in a schema and get some data related to that schema. I want ot count the number of rows for each table and table partition stored in the table object_size_history. I was looking into adding a REF CURSOR so I can loop through the tables, table partitions. The Loop is not working for me. I want to get the count using this syntax: select count(*) FROM <schema name>.<table name> INTO <VARIABLE>. How can I achieve this? I attempted this at the end of the procedure
    CREATE OR REPLACE PROCEDURE calc_object_size (v_schema_name  in varchar2) IS
    TYPE type_cur IS REF CURSOR;
    cur_rows type_cur;
    lv_num_rows number := 0;
    lv_obj_name varchar2(30);
    BEGIN
         INSERT INTO object_size_history (schema_name, object_name, object_type, object_size_mb, count_size_date)
              SELECT OWNER, SEGMENT_NAME, SEGMENT_TYPE, BYTES/(1024*1024), current_timestamp from dba_segments
               WHERE owner = v_schema_name
                 AND segment_type IN ('TABLE','INDEX');
         COMMIT;
         INSERT INTO object_size_history (schema_name, object_name, partition_name, object_type, object_size_mb, count_size_date)
              SELECT OWNER, SEGMENT_NAME, partition_name, SEGMENT_TYPE, BYTES/(1024*1024), current_timestamp from dba_segments
               WHERE owner=v_schema_name
                 AND segment_type IN ('TABLE PARTITION','INDEX PARTITION');
         COMMIT;
         --Now we need a loop that counts the rows for object_type = tables and table partitions, and inserts the count into the object_size_history
         OPEN cur_rows FOR
              select object_name
              from object_size_history
              where object_type in ('TABLE', 'TABLE PARTITION');
         LOOP
              FETCH cur_rows lv_obj_name
                   SELECT count(*) FROM v_schema_name.lv_obj_name
                    INTO lv_num_rows;
                    UPDATE object_size_history
                      SET object_count = lv_num_rows
                        WHERE object_name = lv_obj_name
                           AND object_type IN ('TABLE', 'TABLE PARTITION');
        END LOOP;
         CLOSE cur_rows;
    END;
    /

    Well your specific syntax error is
    FETCH cur_rows INTO lv_obj_name;The whole procedure is a bit of a mess though. You don't need to use a ref cursor for what you are attempting. A normal cursor with the FOR UPDATE OF clause is a better bet. You do have to use dynamic SQL for the other selects, because we can't use a variable in a FROM clause.
    something like this...
    CREATE OR REPLACE PROCEDURE calc_object_size (v_schema_name in varchar2) IS
        lv_num_rows number := 0;
        lv_obj_name varchar2(30);
        CURSOR tabs IS
         select object_name
         from object_size_history
         where object_type in ('TABLE', 'TABLE PARTITION')
         FOR UPDATE OF object_count;
    BEGIN
        INSERT INTO object_size_history (schema_name, object_name, object_type, object_size_mb, count_size_date)
            SELECT OWNER, SEGMENT_NAME, SEGMENT_TYPE, sum(BYTES/(1024*1024)), current_timestamp
            from dba_segments
            WHERE owner = v_schema_name
            AND segment_type IN ('TABLE','INDEX')
            GROUP BY OWNER, SEGMENT_NAME, SEGMENT_TYPE, current_timestamp;
        INSERT INTO object_size_history (schema_name, object_name, partition_name, object_type, object_size_mb, count_size_date)
            SELECT OWNER, SEGMENT_NAME, partition_name, SEGMENT_TYPE, sum(BYTES/(1024*1024)), current_timestamp
            from dba_segments
            WHERE owner=v_schema_name
            AND segment_type IN ('TABLE PARTITION','INDEX PARTITION')
            GROUP BY OWNER, SEGMENT_NAME, SEGMENT_TYPE, current_timestamp;
        OPEN tabs;
        FETCH tabs INTO lv_obj_name;
        LOOP
            EXIT WHEN tabs%NOTFOUND
            EXECUTE IMMEDIATE
                 'SELECT count(*) FROM '||v_schema_name||'.'||lv_obj_name
                 INTO lv_num_rows;
            UPDATE object_size_history
            SET object_count = lv_num_rows
            WHERE CURRENT OF tabs;
        END LOOP;
        CLOSE tabs;
        COMMIT;
    END;
    /Cheers, APC

Maybe you are looking for