3.12. Determining the Number of Records Returned in a DataReader
Problem
You want to determine how many records there are in a DataReader.
Solution
Use one of the following three techniques:
Issue a
COUNT(*)query as part of a batch query. Note that not all data sources support batch queries. If not, execute the statements separately one after the other for a similar result.Iterate over the rows in the
DataReaderand use a counter.Use the
@@ROWCOUNTfunction in a stored procedure to return the number or rows in aDataReaderafter theDataReaderhas been closed. This technique is SQL Server-specific.
The solution uses a single stored procedure:
Person.GetContactsReturns a result set containing all records in the
Person.Contacttable inAdventureWorks. Also, the stored procedure returns the@@ROWCOUNTvalue for the query in an output parameter. The stored procedure is shown in Example 3-15.
Example 3-15. Stored procedure: Person.GetContacts
CREATE PROCEDURE Person.GetContacts
@RowCount int OUTPUT
AS
SET NOCOUNT ON
SELECT * FROM Person.Contact
set @RowCount = @@ROWCOUNT
RETURN @RowCountThe C# code in Program.cs in the project DataReaderRowCount is shown in Example 3-16.
Example 3-16. File: Program.cs for DataReaderRowCount solution
using System; using System.Data; using System.Data.SqlClient; namespace DataReaderRowCount { class Program { static void Main(string[] args) { string sqlConnectString = "Data Source=(local);" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;"; // Batch query ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access