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
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. -
Can u find (number of rows) + (SELECT * FROM emp) in 1 query?
We have a requirement like this: We need to pass a SQL statement as a SYS_REFCURSOR OUT variable from a SP. Problem is, if the SQL returned 0 rows we have to send 1 row with all NULLS to the SYS_REFCURSOR.
Is there any way to find out the number of rows returned from a SQL without having to put a SELECT COUNT(*) again using the "same" SQL?Peter:
That only works if the cursor actually returns rows. Consider:
SQL> create table t as
2 select rownum id, to_char(to_date(rownum, 'J'), 'Jsp') descr
3 from user_objects
4 where rownum <= 5;
Table created.
SQL> insert into t select * from t;
5 rows created.
SQL> commit;
Commit complete.
SQL> create function f (p_id in number) return sys_refcursor as
2 l_cur sys_refcursor;
3 begin
4 open l_cur for
5 select id, descr, count(*) over() cnt
6 from t
7 where id = p_id;
8 return l_cur;
9 end;
10 /
Function created.
SQL> var cur refcursor
SQL> exec :cur := f(1);
PL/SQL procedure successfully completed.
SQL> print cur
ID DESCR CNT
1 One 2
1 One 2
SQL> exec :cur := f(42);
PL/SQL procedure successfully completed.
SQL> print cur
no rows selectedSince the OP's requirement (or ""solution" coming from someone who misunderstood the concept of cursors") is that "if the SQL returned 0 rows we have to send 1 row with all NULLS to the SYS_REFCURSOR" the analytic count doesn't help.
@OP
The only reliable (for certain definitions of reliable) way would be to consume the first row of the cursor to see if it did in fact return any rows.
However, if the cursor was initally empty, we then need to generate a new cursor with all NULLS to satisfy the request. Not a big deal, as the new cursor would reflect the state of the database at the time of the initial query, even if a qualifying row was inserted and committed between the first query and the second, but it doesn't work the other way around.
If I consume the first row and find a record, then I need to re-do the query to get all of the rows. but what happens if another process changes/deletes the qualifying row in between and commits? The second query will have no rows and you will return an empty cursor to the caller.
Also, counting the rows (which the analytic count will need to do) could have a significant impact on performance since all the qualifying rows need to be read before the first row can be returned.
John -
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 knowDavid_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 ?
Glendbms_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 find number of rows in a table
i have one table ,it contains millions of record,how can i know number of rows in that table without using count(*),
i tried in user_table ,for the column NUM_ROWS,but it is not showing number of rows,pls send me a solution for this.
regards,
singhOk, that only was to show simply that max option
might not an option to reduce execution time.Yes, but I/O variances have a tendency to really skew the observed elapsed execution time - making execution time alone a poor choice to determine what SQL will perform better than another.
Both MAX(ROWNUM) and COUNT(*) results in the same amount of I/O - as both uses the exact same execution plan, I/O wise. In this example, a FTS.
SQL> create table testtab nologging as select * from all_objects where rownum < 10001;
Table created.
-- warmed up the buffer cache with a couple of SELECTs against TESTAB in order
-- to discard PIOs from the results
SQL> set autotrace on
SQL> select count(*) from testtab;
COUNT(*)
10000
Execution Plan
Plan hash value: 2656308840
| Id | Operation | Name | Rows | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 35 (9)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | | |
| 2 | TABLE ACCESS FULL| TESTTAB | 9262 | 35 (9)| 00:00:01 |
Note
- dynamic sampling used for this statement
Statistics
0 recursive calls
0 db block gets
131 consistent gets
0 physical reads
0 redo size
223 bytes sent via SQL*Net to client
238 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processed
SQL> select max(rownum) from testtab;
MAX(ROWNUM)
10000
Execution Plan
Plan hash value: 2387991791
| Id | Operation | Name | Rows | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 35 (9)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | | |
| 2 | COUNT | | | | |
| 3 | TABLE ACCESS FULL| TESTTAB | 9262 | 35 (9)| 00:00:01 |
Note
- dynamic sampling used for this statement
Statistics
0 recursive calls
0 db block gets
131 consistent gets
0 physical reads
0 redo size
225 bytes sent via SQL*Net to client
238 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processed
So seeing that we have the exact same baseline for both queries, and that PIO does not influence the results, we time a 1000 executions of both.
SQL> declare
2 cnt number;
3 begin
4 for i in 1..1000
5 loop
6 select count(*) into cnt from testtab;
7 end loop;
8 end;
9 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:03.19
SQL>
SQL> declare
2 cnt number;
3 begin
4 for i in 1..1000
5 loop
6 select max(rownum) into cnt from testtab;
7 end loop;
8 end;
9 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:15.87
SQL>
This shows that what makes the MAX() more expensive is just that - determining the MAX(). For each row, Oracle has to call its internal MAX() function with two values - the current max result and the new value. This function then returns the new max value. This overhead per row adds up to a significant overhead in execution time - making the MAX() approach 5x slower than the COUNT() approach. -
How to find number of rows in tables
Hi,
Can you please help me how to know the number of rows in all the tables databsae.
Thanks In Advance,Just found out that the behaviour changed in 11.2.0.2:
SQL> select * from v$version where rownum = 1
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
1 row selected.
SQL> select owner, table_name, column_value cnt
from (select owner, table_name, 'count(ora:view("' || owner || '","' || table_name || '"))' xq
from all_tables
where table_name in ('EMP', 'DEPT')),
xmltable (xq) order by owner, table_name desc
OWNER TABLE_NAME CNT
FLEET EMP 14
FLEET DEPT 4
MICHAEL EMP 14
MICHAEL DEPT 5
SCOTT EMP 14
SCOTT DEPT 4
STEFAN EMP 14
STEFAN DEPT 4
8 rows selected. -
How to find number of rows after query
I have a simple query page. On this page I enter query criteria and hit the go button I get the query result. (say it finds one record)
On processFormRequest of the controler of this page after I execute (executing explicitly because I am using some bind variable too) the query I print getFetchedRowCount() and getRowCount() and I get 10 (as the total records according bind variable criteria are 10). Where I am expecting 1 as the result.
and I want to get the value of that row as well.
Can anyone please guide me how I can achieve this?
ThanksYes I am using queryBean for search region. I can see both, criteria that I am passing through search region and bind variable in the query.
If I pass the customer name it gives me that customer as a result.
but the counts i get doesn't seem to consider that search criteria from query region.
Interestingly when I execute the query again with the same customer name ...I get the correct count. i.e 1
Followoing is the query from "about this page-->business component reference details."
SELECT * FROM
select distinct super_customers.party_name
customer_name,
super_cust.cust_account_id customer_id,
sup_cust_acct.Status,
sup_cust_acct.customer_class_code,
CINT_CRM.Get_Customer_Type(sup_cust_acct.customer_type),
sup_cust_acct.FOB_Point,
sup_cust_acct.sales_channel_code,
From
hz_parties Customers,
hz_parties Super_Customers,
hz_parties cust_cont_rel,
HZ_RELATIONSHIPS REL,
HZ_Cust_Accounts rel_cust_acct,
HZ_Cust_Accounts sup_cust_acct,
HZ_CUST_ACCT_RELATE_ALL Super_Cust
where
customers.party_id = rel.subject_id
and cust_cont_rel.party_id = rel.party_id
and rel_cust_acct.party_id = customers.party_id
and Super_Cust.related_cust_account_id = rel_cust_Acct.cust_account_id
and super_cust.cust_account_id = sup_cust_acct.cust_account_id
and Super_Customers.party_id = sup_cust_acct.party_id
and sup_cust_acct.account_number like 'SC%'
and cust_cont_rel.status = 'A'
and rel.status = 'A'
and rel_cust_acct.status = 'A'
and Super_Cust.status = 'A'
and sup_cust_acct.account_number like nvl(:customerNumber, sup_cust_acct.account_number)
and nvl(rel.object_id, -1) = nvl(nvl(:contactPartyId, rel.object_id), -1)
and upper(super_customers.party_name) like upper(nvl(:customerName, super_customers.party_name))
and sup_cust_acct.account_number like 'SC%') QRSLT
WHERE
(( UPPER(CUSTOMER_NAME) like UPPER(:5)
AND (CUSTOMER_NAME like :6
OR CUSTOMER_NAME like :7
OR CUSTOMER_NAME like :8
OR CUSTOMER_NAME like :9)) -
How to find number of rows inserted by dynamic query
EXECUTE IMMEDIATE l_sql
USING p_start_date, p_end_date
RETURN sql%rowcount into l_count;
Here l_sql is is selecting record from table_1 based on p_start_date, p_end_date and inserting record in table_2.
There is some further process to be done on table_2 which I want to do only if atleast 1 record is inersted in table_2 by the select query on table_1 for this I am using RETURN sql%rowcount into l_count;
I am geting error pls-00103 for this.
Is there any way to achieve this functionality.
ThanksIs there any way to achieve this functionality.Depends on your exact form of l_sql. Here are two ways to get the rowcount out of execute immediate:
SQL> create table emp_test as select * from emp where 1=2
Table created.
SQL> begin
execute immediate 'insert into emp_test select * from emp';
dbms_output.put_line ('Count: ' || sql%rowcount);
end;
Count: 14
SQL> rollback
Rollback complete.
SQL> declare
l_count integer;
begin
execute immediate 'begin insert into emp_test select * from emp; :1 := sql%rowcount; end;' using out l_count;
dbms_output.put_line ('Count: ' || l_count);
end;
Count: 14
PL/SQL procedure successfully completed. -
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.
TIAcreate 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 -
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 -
In ABAP reports, is there any logic to find number of rows in Excel sheet.
Regards,
Naseer.Hi,
Try this code...
REPORT zreport.
PARAMETER p_infile LIKE rlgrap-filename DEFAULT 'C:TEMPZMPR.xls'.
DATA : lin TYPE i.
DATA: itab LIKE alsmex_tabline OCCURS 0 WITH HEADER LINE.
START-OF-SELECTION.
CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'
EXPORTING
filename = p_infile
i_begin_col = '1'
i_begin_row = '1'
i_end_col = '1'
i_end_row = '28000'
TABLES
intern = itab
EXCEPTIONS
inconsistent_parameters = 1
upload_ole = 2
OTHERS = 3.
IF sy-subrc <> 0.
MESSAGE text-009 TYPE 'S'. "Problem uploading Excel Spreadsheet
EXIT.
ENDIF.
DESCRIBE TABLE itab LINES lin.
WRITE :/ 'Number of lines: ', lin. -
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 -
Hi,
I need to query in max db to find number of rows exist in each and every table. Is there any query we can use to find in a single shot?
Example:
S.NO Table Name Number of rows
1 A 3000
2 B 5000Hi,
it depends on the database version you are using. In the newer database versions 7.8 and 7.9 you can use the system table files to get the total number of records.
SELECT sum (entrycount) from files where type = 'TABLE'
This includes the MaxDb systemtables as well.
If you want to count the number of rows of one schema only use the following join command between tables and files:
SELECT sum(entrycount) from files f, tables t where f.type = 'TABLE'
AND tableid = fileid and SCHEMANAME = '<schema>'
e.g.
SELECT sum(entrycount) from files f, tables t where f.type = 'TABLE'
AND tableid = fileid and SCHEMANAME = 'SUPERU'
The system table files contains for each table the entrycount, which is exaclty the number of records.
Precondition: All file directory counters for all tables have been created sucessfully. This is the case if table Sysupdatecounterwanted is empty. The creation is implictely executed.
Regards, Christiane -
Number Of rows invisible ? in pagination
hi,
My info :
Oracle 11g
Application Express 3.2.1.00.12
Maybe this is a newbie question, but nowhere i can see the "number of rows" field in the Report Attributes > Pagination.
I do see "Maximum Row Count", but not the Number of rows displayed on a single page.
I checked the documentation
http://www.oracle.com/technology/products/database/application_express/howtos/howto_report_rownum.html
And its supposed to be there, but not on my version.
Also i see in the documentation the part is called "Layout and Pagination", but its just called Pagination for me.
Could anyone point me to where i can set the number of rows displayed on a single page of a report ?
ThanksThank you Pedro for your answer, but the problem is: i cannot find "Number of Rows " in the Pagination area (read my post ;) )
I have been looking everywhere for it, i looked on all documentations, it SHOULD be here, but unfortunately, i dont see it.
Here are the fields visible in Pagination :
Pagination
Pagination Type
Pagination Display Position
Show Null Values as
Maximum Row Count
When more than maximum row data found message
When No Data Found Message
Regards
Maybe you are looking for
-
Can't install Windows 8.1 - Driver Violation
I'm trying to install Windows 8.1 on my Asus U43JC notebook. Windows 8 will install fine without a problem, but I can't get 8.1 installed. When installing from the marketplace, 8.1 will download and install, but after first booting, I get a blue scre
-
2 iPhones, 1 iTunes Account, and 1 or 2 iCloud Accounts???
I have 2 iPhone 4, a Macbook Pro, Macbook, Mac Mini, and Apple TV. I am trying to setup the 2 phones to share to same iTunes account, contacts, and calendars. However, I need each device to have different apps and backup to iCloud. Can i use 2 diff
-
How to bring search field back in Mountain Lion?
To the third-party developers reading here: Is it possible to bring back the separate search field in the upcoming Safari in Mountain Lion? The websearch from the addressbar is THE killer feature: to kill Safari from my favourite software list. I do
-
Recursive query for finding parents and children against two tables
Hi I have two tables where the data is stored hierarchially. I have found using connect_by, level and other oracle functions doing its job when the data is in one table. Can I traverse against two tables by using the same oracle functions. My Table A
-
A Parsing problem...
Hi Guys... I am writing a program that is used to write memos. The memos when stored are writen in XML format, they have a title and the body. The problem is that when the file is read by parsing it using a XML parser the memos dont show the body, th