Counting Records

[ Team LiB ] Recipe Counting Records Problem You want to determine how many rows that meet certain criteria are in a table. Solution Use the ExecuteScalar( ) method of the Command object to determine the number of records in the table. | Team LiB Recipe Counting Records Problem You want to determine how many rows that meet certain criteria are in a table. Solution Use the ExecuteScalar method of the Command object to determine the number of records in the table. The sample code executes the COUNT function on the results of a query returning rows from the Orders table in the Northwind sample database where the rows match a user-specified CustomerlD. The C code is shown in Example 10-5. Example 10-5. File Namespaces variables and constants using System using using using . . . Create the connection. SqlConnection conn new SqlConnection Sql_ConnectString Build the query to count including CustomerlD criteria if specified. String selectText SELECT COUNT FROM Orders if selectText WHERE CustomerId . Create the command to count the records. SqlCommand cmd new SqlCommand selectText conn Execute the command storing the results. int recordCount int Discussion The ExecuteScalar method of the Command object returns a single value from a query rather than a table or a data stream. If the query returns a result set this method returns the value of the first column of the first row. The number of records matching certain criteria can be determined by executing a SQL statement that returns the COUNT aggregate function and including a WHERE clause that specifies the criteria. Use the ExecuteScalar method to execute the statement and return the count. Cast the result to an integer data type. This technique can also be used with other aggregate functions to determine values such as averages or sums. For more information about aggregate functions see Microsoft SQL Server Books Online. Team LiB

Bấm vào đây để xem trước nội dung
TÀI LIỆU MỚI ĐĂNG
63    337    2    14-05-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.