Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4147
  • Last Modified:

How to Get Record Count For ExecuteReader();

Hi,

I know you can get a records affected with ExecuteNonQuery and that you can get a rowcount with ExecuteReader if you are using SqlServer to get an output parameter with the @@ROWCOUNT but I think you can only retreive the @@ROWCOUNTafter closing the connection.  

How then can I get some kind of rowcount before the connection closes?  For example, I want to say, if there is a record then make myVar1=dr[0].ToString(); myVar2=dr[1].ToString(); etc.?  If I can only get the @@ROWCOUNT after closing the connection then I can't really set the variables beforehand because there may not be a record existing.

Where and what do I do to the following?:

SqlDataReader dr=cmd.ExecuteReader();
dr.Read();

//If record exists then set these variables:

myVar1=dr1[0].ToString();
myVar2=dr1[1].ToString();

//Else...do something

myConn.Close();

Thanks
0
champ_010
Asked:
champ_010
  • 3
  • 2
1 Solution
 
daffodilsCommented:
You want to check just IF ANY records exist ? or do you want to know HOW MANY records are there ?
0
 
champ_010Author Commented:

Hmmm...I guess in my current situation it is IF ANY records exists.
0
 
daffodilsCommented:
So,

1. If you want to check just IF ANY records exist ? then you can use SqlDataReader.HasRows Property

if(dr.HasRows)
{
    myVar1=dr1[0].ToString();
    myVar2=dr1[1].ToString();
}
Gets a value indicating whether the SqlDataReader contains one or more rows.
Note --> This namespace, class, or member is supported only in version 1.1 of the .NET Framework.


2. And If you want to know HOW MANY records are there ? you have SqlDataReader.RecordsAffected Property

Gets the number of rows changed, inserted, or deleted by execution of the Transact-SQL statement.

BUT, this property is not set until all rows are read and you close the SqlDataReader.
0
 
champ_010Author Commented:

THANKS!  An important question answered--will be using it alot!
0
 
daffodilsCommented:
sure.. glad I could help.
This is the MSDN article for SqlDataReader Members.. thought you might like it as a reference.
Best of Luck !

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatasqlclientsqldatareadermemberstopic.asp
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now