Number of rows in cursor

I believe this might have been asked multilpe times, but I could not find anything.
Is there any way to get the number of rows in a cursor, when I open the cursor. In my case, I have to do the processing in 3 different ways depending on whether the cursor has A)no rows, B) One row, c) more than one row. I know I can get the number of rows by fetching all the rows and then getting the %rowcount.
I wanted to know whether its possible before fetching any row. The ways I am currently doing it is as follows
blah blah blah is
Cursor cur = <my cursor query>;
cont number;
BEGIN
select count(*) into cont from <things exactly same as my cursor query>
if (cont = 0) THEN
<Processing A>
ELSIF (cont = 1) THEN
<Processing B>
ELSE
<Processing C>
END IF;
END
Is this method better than getting the the cursor, fetching at least 2 rows, if the rowcount is more than one, close the cursor and do the processing based on the rowcount i've got.
TIA

create or replace
package Y1 is
   procedure do_it (p_1 number) ;
end Y1;
create or replace
package body Y1 is
   procedure do_it (p_1 number) is
      cursor c1_cur (p_1 number) is
        select tname from tab where rownum <= p_1
      c1_rec c1_cur%rowtype ;
      c2_rec c1_cur%rowtype ;
      l_count  number ;
   begin
      l_count  := 0 ;
      open c1_cur(p_1) ;
      LOOP
         if l_count = 0 then
            fetch c1_cur into c1_rec ;
         else
            fetch c1_cur into c2_rec ;
         end if ;
         exit when c1_cur%notfound ;
         l_count  := l_count + 1 ;
         if l_count = 2 then
            dbms_output.put_line ('XXX=2') ;  
            dbms_output.put_line (c1_rec.tname) ;
            dbms_output.put_line (c2_rec.tname) ;
         elsif l_count > 2 then
            dbms_output.put_line ('XXX>2') ; 
            dbms_output.put_line (c2_rec.tname) ;
         end if ;
      END LOOP ;
      close c1_cur ;
      if l_count = 0 then
         dbms_output.put_line ('XXX=0') ;
         dbms_output.put_line ('===========================') ;
      elsif l_count = 1 then
         dbms_output.put_line ('XXX=1') ;
         dbms_output.put_line (c1_rec.tname) ;
         dbms_output.put_line ('===========================') ;
      else
         dbms_output.put_line ('===========================') ;
      end if ;
   end do_it ;
end Y1;
SQL> set serveroutput on
SQL> exec Y1.do_it (0)  -- etc                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Specify the number of rows in Cursor

    Hi,
    Can anyone tell me, if there is some way where i can specify the number of rows to be fetched in a single cursor.
    As in, The first fetch 100 rows, second 100 and so on
    Regards,
    Rishav

    Hi
    Use the option PACKAGE
    FETCH NEXT CURSOR <CURSOR> INTO TABLE <int table> PACKAGE SIZE 100.
    Max

  • Maximu number of rows in cursor

    Hi,
    How many rows i can fetch into the cursor.
    is there any restriction.
    when the number of rows increase will the db face the slowness?
    Thanks
    siva

    thanks
    this is my code
    CREATE OR REPLACE PROCEDURE PRC_FILE_UPLOAD(n_eodid NUMBER,job_id NUMBER,return_status OUT VARCHAR2) IS
    n_col          NUMBER(10);
    n_colcnt      NUMBER(10) :=0 ;
    v_eodmetadata     EOD_METADATA_DET%ROWTYPE;
    v_eodtable     VARCHAR2(100);
    sql_stmt      VARCHAR2(4000);
    sql_stmt1      VARCHAR2(4000);
    colval      varchar2(4000);
    eodid          NUMBER(10) := n_eodid;
    jid          NUMBER(10) := job_id;
    charbuf VARCHAR2(4000);
    lopcnt     NUMBER(10) :=0 ;
    s          NUMBER(10) :=0 ;
    vals          VARCHAR2(4000);
    no_data      EXCEPTION;
    result     VARCHAR2(100);
    CURSOR clob_ins IS SELECT * FROM EOD_METADATA_DET WHERE eod_id = EODID
    AND UPPER(ORCL_COL_NME) !='FILLER' ORDER BY SEQ;
    BEGIN
    OPEN clob_inS;
    LOOP
    FETCH clob_ins INTO v_eodmetadata;
         v_eodtable := v_eodmetadata.orcl_tbl_nme;
    EXIT WHEN clob_ins%notfound;
    colval := colval||' '||v_eodmetadata.ORCL_col_NME||',' ;
    n_col := v_eodmetadata.col_size;
    END LOOP;
    sql_stmt := 'INSERT INTO '||v_eodtable||'(';
    sql_stmt1 := sql_stmt||COLVAL;
    sql_stmt1 := SUBSTR(sql_stmt1,1,LENGTH(sql_stmt1)-1)||')VALUES';
    CLOSE clob_ins;
    FOR jval IN (SELECT * FROM EOD_FLAT_DATA)
    LOOP
    lopcnt := 0;
    n_colcnt :=0;
    s:=s+1;
    IF s <= 1 THEN
    s:=s+1;
    ELSE /* from second row onwards */
    charbuf := jval.EODDATA;
    FOR seq IN (SELECT col_size,TYPE FROM EOD_METADATA_DET WHERE eod_id = EODID AND UPPER(ORCL_COL_NME) !='FILLER'
    ORDER BY SEQ)
    LOOP
    n_col := seq.col_size;
    lopcnt := lopcnt + 1;
    IF lopcnt = 1 THEN /* for first column WIDTH */
    vals := SUBSTR(charbuf,1,n_col);
    n_colcnt := n_colcnt + n_col;
    ELSE
    IF seq.type = 'CHAR' THEN
    vals := vals||','||''''||SUBSTR(charbuf,n_colcnt+1,n_col)||'''';
    ELSIF seq.type = 'NMBR' THEN
    vals := vals||','||SUBSTR(charbuf,n_colcnt+1,n_col);
    ELSIF seq.type = 'DATE' THEN
    VALS := vals||','||''''||to_char(to_date(SUBSTR(charbuf,n_colcnt+1,n_col),'dd/mm/RR'),'dd-mon-yyyy')||'''';
    ELSE
    vals := vals||','||''''||SUBSTR(charbuf,n_colcnt+1,n_col)||'''';
    END IF;
    n_colcnt := n_colcnt + n_col;
    END IF;
    END LOOP;
    END IF;
    IF length(vals)>1 THEN
    sql_stmt1 := sql_stmt1||'('||vals||')';
    EXECUTE IMMEDIATE sql_stmt1;
    return_status := 'SUCCESS';
    result := return_status;
    END IF;
    END LOOP;
    EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
    return_status := 1;
    result := return_status;
    RAISE_APPLICATION_ERROR(-20010,'UNIQUE CONSTRAINT VIOLATION ERROR');
    WHEN OTHERS THEN
    return_status := 'FAILED';
    result := return_status;
    RAISE_APPLICATION_ERROR(-20010,'CHECK UR INSERT STATEMENT');
    END PRC_FILE_UPLOAD;

  • How to get the total count of the no. or rows a cursor has fetched

    Hi All,
    Is there a way to get the number of rows a cursor query has fetched, without looping into the cursor and using a counter variable
    I mean like in pl/sql table we can directly use the pl/sql table attribute .count is there a way to achieve this in cursor
    thanks a lot in advance

    Qwerty wrote:
    Is there a way to get the number of rows a cursor query has fetched, without looping into the cursor and using a counter variableYes.
    It is zero.
    On the first loop and first fetch it will be 1, second 2 etc.
    This is because cursors have no rows, or fetch no rows until your code or the client uses the cursor to fetch them.
    I mean like in pl/sql table we can directly use the pl/sql table attributeA PL/SQL array is not like a cursor, a PL/SQL array has the rows already fetched into it.
    A cursor is not an array but a pointer to a compiled SQL statement so you cannot count how many rows it has, because it has none. You can only count how many rows you fetch from it.

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

  • How to get the number of rows in a DB-Cursor

    When i open a database cursor i do not know how much rows are stored in the cursor. To solve this problem i have to send a 'select count(1) ...' to get the number of rows before i set up the cursor. I think that this is not very clever and could possibly cause performance problems. But i need the num of rows to show the percentage of processed rows. Is there any other way to get the num of rows? May be by checking the cursor directly?
    Please help!
    Thanx a lot

    In order to find out how may rows are going to be processed, oracle has to visit every row. So with a cursor, there is no property that will accurately reflect the number of rows until you get to the last one. That said, you could use
    select count(*) over() as row_count, <rest of your columns> FROM <your table>
    which will give you the total row count agaist each row in the result set. There are performance penalties involved but they will be less than issuing the query twice, once to get the count and once to get the rows.
    Have a look on asktom for some very usefull info about all this.
    HTH

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

  • Find number of rows in  a cursor

    How can i find how many rows are in a cursor. I have a situation if my cursor only retruns one row i return the data if it returns more then one row i will need to do additional select.

    If you have logic like this
    SELECT COUNT(*)
      INTO l_cnt
      FROM emp
    WHERE deptno = p_deptno;
    IF( l_cnt > 1 )
    THEN
      FOR x IN (SELECT * FROM emp WHERE deptno = p_deptno)
      LOOP
        ..where you are counting the rows and then later fetching them, getting the count and then getting the rows will force Oracle to do the work of the query twice. It will also potentially cause logic errors because the number of rows returned by the COUNT(*) won't necessarily match the number of rows fetched from the cursor because some other session may have committed changes between your session executing those two statements.
    Can you describe the logic you are trying to implement in a bit more detail? There are potentially a number of different approaches depending on exactly what you are trying to do. Sometimes it may make sense to do a COUNT(*), sometimes it may make sense to fetch the data into a collection, count the collection elements, and then operate on the collection, sometimes it may make sense to do a SELECT INTO and handle the exception if the wrong number of rows are returned, etc.
    Justin

  • UNABLE TO SHOW EXACTLY NUMBER ROWS INTO CURSOR

    CAN ANYONE TELL ME WHY I CAN'T SHOW THE EXACT NUMBER OF ROWS FROM A CURSOR INTO A CONTROL BLOCK FROM FORMS 6i?.
    I WROTE THIS SIMPLE CODE:
    DECLARE
    CURSOR c_CURSOR1 IS
    SELECT COL1, COL2... COLN
    FROM TABLE1
    WHERE COND1...CONDN
    ORDER BY COL1
    BEGIN
    GO_BLOCK('BLOCK');
    CLEAR_FORM;
    FIRST_RECORD;
    FOR v_var IN c_CURSOR1 LOOP
    :item1 := v_var.col1;
    :item2 := v_var.col2;
    NEXT_RECORD;
    END LOOP;
    END;
    I CAN ONLY SEE THE LAST RECORD.
    IT'S REQUERIED TO INSTAL ANY PARCH, IS THAT A BUG?

    This is answered in the duplicate thread:
    Re: General Database Name and SID
    Regards,
    Robin Zimmermann
    Forms Product Management

  • Cursor & large number of rows

    hello !
    i have an application wich interrogates my Oracle 8i Databse using OCI, my problem is that the number of rows returned is so large ( the totality of rows is 1 million) , how can i have rows returned by packets (as the same way as results returned by a search tool)

    Use bulk binds (see http://technet.oracle.com/sample_code/tech/pl_sql/htdocs/bulkdemo.txt)
    hello !
    i have an application wich interrogates my Oracle 8i Databse using OCI, my problem is that the number of rows returned is so large ( the totality of rows is 1 million) , how can i have rows returned by packets (as the same way as results returned by a search tool)

  • How to count number of rows as well as the sum of a column in a procedure

    Hi, i need to count the number of rows a sql returns in a procedure.
    as well as i need to sum up a different column.
    i need the following output:
    count the number of rows output
    and sum the total column
    code:
    procedure samba_extraction (p_errmsg IN out varchar2
    ,p_errcode IN out NUMBER
    ,p_filename in varchar2
    ,p_start_date varchar2
    ,p_end_date varchar2)
    is
    file_handle utl_file.file_type; -- file handle of os flat file
    -- cursor to select the c_samba_resources
    cursor c_samba is
    select
    lpad(h.contract_number,15,'0') contract_number
    ,h.short_description description
    ,h.attribute_category context_value
    ,h.attribute7 samba
    ,h.attribute8 samba_number
    ,h.start_date start_date
    ,h.end_date end_date
    ,h.sts_code active_inactive
    ,l.price_negotiated price
    ,l.tax_amount tax
    ,LTRIM(to_char((l.price_negotiated + l.tax_amount),'00000000.00')) total
    from
    oks_auth_headers_v h
    ,oks_auth_lines_v l
    where h.id = l.chr_id
    and ((h.start_date <= (p_end_date))
    and (h.end_date >= (p_start_date)))
    and h.attribute7 = 'SAMBA'
    -- and h.sts_code = 'ACTIVE'
    and ((h.attribute_category = 'SUBSCRIPTION.DURATION')
    or (h.attribute_category = 'SUBSCRIPTION.VALUE')
    or (h.attribute_category ='SUBSCRIPTION.QUANTITY'));
    l_output varchar2(1000);
    l_counter varchar2(11);
    l_total varchar2(11);
    l_filename varchar2(30);
    begin
    if p_filename IS NOT NULL then
    -- l_batch_no := 'T';
    l_filename := p_filename || '.txt';
    -- open file to write into and obtain its file_handle.
    file_handle := utl_file.fopen('/usr/tmp',l_filename,'W');
    fnd_file.put_line(fnd_file.log,'The '|| l_filename||' file you have requested has been placed in the usr/tmp directory');
    for l_info in c_samba
    loop
    -- l_output := null;
    l_output := l_info.samba_number||'+'||l_info.total||l_info.contract_number;
    utl_file.put_line(file_handle,l_output);
    fnd_file.put_line(fnd_file.output, l_output);
    dbms_output.put_line(l_output);
    end loop;
    else
    p_errmsg := ('Please enter a filename for this file ');
    write_log('UPDATE : ' ||p_errmsg);
    end if;
    -- close the file.
    utl_file.fclose(file_handle);
    exception
    when no_data_found then
    dbms_output.put_line('no_data_found');
    utl_file.fclose(file_handle);
    when utl_file.invalid_path then
    dbms_output.put_line('UTL_FILE.INVALID_PATH');
    utl_file.fclose(file_handle);
    when utl_file.read_error then
    dbms_output.put_line(' UTL_FILE.READ_ERROR');
    utl_file.fclose(file_handle);
    when utl_file.write_error then
    dbms_output.put_line('UTL_FILE.WRITE_ERROR');
    utl_file.fclose(file_handle);
    when others then
    dbms_output.put_line('other stuff');
    utl_file.fclose(file_handle);
    end samba_extraction;
    end xx_samba;

    Hi,
    Initialise one variable TOT_ROWS to 0.
    Then in the for loop
    tot_rows := tot_rows + +1 ;
    so after for loop the value in the tot_rows will be the total records..
    If u want it to get this value in the calling procedure of this , just declare tot_rows parameter as out parameter.
    For sum of a column:
    Initialise a variable sum_col to 0.
    In the for loop
    sum_col := sum_col+I_info.column_name
    aprameter if u wish return this value as out..
    I think this wil give u the o/p..
    cheers,
    Sivarama

  • How to Display Number of Rows Deleted/Inserted etc... in PL/SQL

    In Oracle 10g PL/SQL, I have a delete statement in a stored procedure. It is not in a cursor. I want to see the number of rows I've deleted. I can use the dbms_output.put_line package. I should know this, but I don't have time to perfect the syntax. How would I get the number of rows that get deleted and display it via dbms_output.put_lline?

    No time to google either I guess.
    http://www.google.co.uk/search?q=number+of+rows+deleted+oracle&rls=com.microsoft:en-gb&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1&rlz=&redir_esc=&ei=Qi5qToGyGYqw8QOGzf3nAg
    SQL> create table dt_del_ex(id number);
    Table created.
    SQL> set serveroutput on
    SQL> BEGIN
      2
      3      INSERT INTO dt_del_ex VALUES(1);
      4
      5      DBMS_OUTPUT.put_line(TO_CHAR(SQL%ROWCOUNT)||' rows inserted');
      6
      7      INSERT INTO dt_del_ex select rownum from dual connect by level <=10;
      8
      9      DBMS_OUTPUT.put_line(TO_CHAR(SQL%ROWCOUNT)||' rows inserted');
    10
    11      UPDATE dt_del_ex SET id = id + 3 WHERE id >= 9;
    12
    13      DBMS_OUTPUT.put_line(TO_CHAR(SQL%ROWCOUNT)||' rows updated');
    14
    15      DELETE FROM dt_del_ex WHERE id <= 10;
    16
    17      DBMS_OUTPUT.put_line(TO_CHAR(SQL%ROWCOUNT)||' rows deleted');
    18
    19  END;
    20  /
    1 rows inserted
    10 rows inserted
    2 rows updated
    9 rows deleted
    PL/SQL procedure successfully completed.

  • How do I limit the number of rows retrieved at a time using RefCursor?

    I have a PL/SQL package in use, that returns a REF CURSOR. This is currently being used in a Forms 6i application. Now I want to develop an ASP.NET web application that displays exactly the same information as my Forms 6i module. In fact those two applications will be used concurrently for a while.
    I looked at the sample code provided on otn.oracle.com and decided to use the OracleDataAdapter.Fill()-method to fill a dataset and bind that dataset to a pageable GridView. Now I wonder, whether this method retrieves ALL records of the query at once and how I can limit the number of rows fetched? The Select statement retrieves up to 10000 rows at a time. Most of the time, a user is only interested in the first 20-30 rows. Forms 6i fetches more rows as the user scrolls down, how can I implement the same behavior in ODP.NET?
    - Markus

    Excuse me, but the reply does not quite answer my question. Maybe I did not explain my concerns clear enough:
    I understand the use of the two properties (RowSize and FetchSize) to reduce the amount of round trips needed to transfer the data - not the number of rows fetched in total. This would still lead to a situation where all rows are transferred, when I am using the OracleDataAdapter.Fill()-Method. Is this correct or did I misunderstand the function of this method?
    I quote the otherwise really helpful article you send me:
    Of course, there is a cost if the fetch size is arbitrarily large. More client-side memory and processor cycles will be needed to store and manage a larger amount of data. The goal is to find a high-performing balance between the number of round trips and the amount of data retrieved per trip.
    My RowSize is for sure a bit larger than the one in the given example. The query will probably be used by up to 100 users at a time, so I would like to limit the resource-costs not only on the network by the number of round trips, but also on the web-server which is storing all these records in it's memory per user-request.

  • Trying to find the number of rows in a ResultSet

    I am trying to find the number of rows in a ResultSet, using the following code:
    rs = st.executeQuery(query);
    rs.last(); // to move the cursor to the last row
    System.out.println(rs.getRow());
    However, I am getting this error:
    java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Unsupported method: ResultSet.last
    Whats going wrong??

    praveen_potru wrote:
    You might have not used scrollable result set..
    Try like this:
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);rs = stmt.executeQuery(sqlString);
    // Point to the last row in resultset.
    rs.last();
    // Get the row position which is also the number of rows in the ResultSet.
    int rowcount = rs.getRow();
    System.out.println("Total rows for the query: "+rowcount);
    cheersAnd I hope the OP would read it because the thread is a year old.

Maybe you are looking for

  • Macbook pro 15 inch (2010 late) crashing

    Hello, i have been having many problems with my macbook pro in recent months.  i got it repaired by apple technician becouse i have my applecare warranty running. now it will be the 3 time they change the mother board and graphic card. all of those r

  • Database Link gives Ora-12535 error

    I have Oracle 9i Release 2 on NT 4 box. I am attempting to connect to an Oracle 8i Database via a database link. I am able to connect to the database using my username and password throught Toad. I can see the tables that I am trying to query through

  • Data getting posted on refreshing IE's refresh button..how to stop

    Hi , we have beent rying to resolve this issue. the problem is when we click on submit button data getting posted on to mobile devices and in the next page "message has been sent " text will come.but if refresh button is clicked again data getting po

  • I tried to download the flash player and my computer doesnt want to! Or, any other downloads!

    [picture removed by host] Why does my computer not want to download anything? It says " could not be downloaded". No explanation, or anything! Might be my settings but, Im not real computer savey!   Im trying to download the flash player!!!! Help!? T

  • I cannot drag or copy and paste files. 10.5.8

    Yesterday my MacBook Pro was working fine. Today I cannot drag files or cut and paste. I have rebooted  and repaired permissions. Nothing! i did trash some files late last night, but thought they were jpegs and quictimes. Any fresh help?