Record count in SqlDataReader

C

Charlie@CBFC

Hi:

When returning an SqlDataReader from a database query, how do you get a
count of the number of records contained in the reader? There is no "Count"
property for reader object.

Thanks,
Charlie
 
A

Andrew Robinson

A reader doesn't have a count. You will need to read all the records and
keep track of count yourself.

Better to use a Command.ExecuteScalar() or to use a dataAdaptor and load
your records into a DataSet or Table and get your count there.

using (SqlConnection cn = new SqlConnection(DataConnection))
using (SqlCommand cm = new SqlCommand("SELECT Count(*) FROM MyTable", cn))

{

cn.Open();

cm.CommandType = CommandType.Text;

int i = (int)cm.ExecuteScalar();

cn.Close();

return i;

}
 
B

Brock Allen

There is no count because the reader is streaming the results in form the
DB server. IOW, it's possible the DB server is still finding records that
match your criteria after you start using the data reader.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top