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();
?
No.
IDataReader
is a simple forward-only view of a resultset; it cannot get a count.
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.
Well past the date posted but there is a way, that worked for me took a while to get because i suck at wording my google searches.
dbCommand.Connection.Open();
//dbReader = dbCommand.ExecuteReader(); I left this here to show not to do the read
searchCount = dbCommand.ExecuteScalar(); // this line returns the value count
// from my tests on my reader it works perfectly
Maybe not an good idea, but i got count using variable inside while loop. This code work fine for me:
IDataReader reader = SqlHelper.ExecuteReader(sqlConnectionString, Procedure.GetSuperUserOwnerDetails, ProfileName);
int count = 0;
while (reader.Read())
{
count = count + 1;
}
lblProfileOperator.Text = " Owner : " + count;
The count of rows calculated only when you read the DataReader but i didnt get it , why you want to know the rows count before reading it.
精彩评论