Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing count from an SQL query

Tags:

c#

sql

sql-server

What is the simplest way in C# (.cs file) to get the count from the SQL command

SELECT COUNT(*) FROM table_name 

into an int variable?

like image 668
Sebastjan Avatar asked Jan 12 '11 12:01

Sebastjan


People also ask

How do you get a count in SQL query?

In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.

Is there a count function in SQL?

The COUNT() function is one of the most useful aggregate functions in SQL. Counting the total number of orders by a customer in the last few days, the number of unique visitors who bought a museum ticket, or the number of employees in a department, can all be done using the COUNT() function.


2 Answers

Use SqlCommand.ExecuteScalar() and cast it to an int:

cmd.CommandText = "SELECT COUNT(*) FROM table_name"; Int32 count = (Int32) cmd.ExecuteScalar(); 
like image 72
m.edmondson Avatar answered Sep 28 '22 01:09

m.edmondson


SqlConnection conn = new SqlConnection("ConnectionString"); conn.Open(); SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn); Int32 count = (Int32) comm .ExecuteScalar(); 
like image 24
Rami Alshareef Avatar answered Sep 27 '22 23:09

Rami Alshareef