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?
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.
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.
Use SqlCommand.ExecuteScalar() and cast it to an int
:
cmd.CommandText = "SELECT COUNT(*) FROM table_name"; Int32 count = (Int32) cmd.ExecuteScalar();
SqlConnection conn = new SqlConnection("ConnectionString"); conn.Open(); SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn); Int32 count = (Int32) comm .ExecuteScalar();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With