Your query always returns a single row, even rows do not exist. It will return 0 if WHEREthere are no rows for your condition
Use SqlCommand.ExecuteScalar Method ()
using (var con = new SqlConnection("ConnectionString"))
{
con.Open();
string query = "SELECT COUNT(*) FROM Some_Table WHERE Val > 5";
using (var cmd = new SqlCommand(query, con))
{
int rowsAmount = (int)cmd.ExecuteScalar();
if (rowsAmount > 0)
{
Console.WriteLine("Returned more than 0 rows");
}
else
{
Console.WriteLine("Did not return more than 0 rows");
}
Console.ReadLine();
}
ScalarValuewill return the first column of the first row of the query result. Therefore, for your request this is a more effective method of obtaining the necessary information.
Fabio source
share