Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SqlDataReader count rows??

Status
Not open for further replies.

djam

Technical User
Nov 15, 2002
223
CA
is there a way to count the rows returned from a SqlDataReader??

I don't want to make two calls the the DB if its not necessary...

thanks

" ahhh computers, how they made our lives much simpler ;) "
 
When you have a SqlDataReader object, you can count only the records when iterating the reader:
int iCount=0;
while(myReader.Read())
{
iCount++;
}
myReader.Close();
If you are interested to count only the records returned by a query then use ExecuteScalar() instead of using a DataReader object:
string mySQL="select ....";
string myScalarQuery= "select count(*) as NumberOfRecords from (" + sSQL + ") as t1";

SqlCommand myCommand = new SqlCommand(myScalarQuery, myConnection);
myCommand.CommandText = myScalarQuery;
myCommand.Connection.Open();
Int32 iCount = (int) ExecuteScalar();
-obislavu-
 
Or what I did was, I added a Count(*) column to the SQL SELECT so each row will contain an additional column that has # of rows returned, eventhough the data is redundant, we can avoid an additional call.

-Kris
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top