Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDataReader - Any way to get the total rows?

Is there any way to get the total number of rows returned from a SQL query (from the IDataReader) before iterating through the rows by using reader.Read();?

like image 525
michael Avatar asked Jul 18 '11 14:07

michael


2 Answers

No.

IDataReader is a simple forward-only view of a resultset; it cannot get a count.

like image 64
SLaks Avatar answered Nov 03 '22 14:11

SLaks


No, the datareader will not return a count first. However, if you do need to do it, use two queries that return multiple result sets.

for example in SQL Server:

sql = "SELECT COUNT(1) FROM A; SELECT * FROM A;"

Iterate the result sets. Use the IDataReader on the second result set.

The database server should be able to do this quite fast if it is using appropriate indexes.

like image 6
sgtz Avatar answered Nov 03 '22 15:11

sgtz