Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SQL if query returns any rows count

What is the simplest and most efficient way to find if a data returns using a query? I'm using DataTable like sqlAdapter.Fill(_table1) and then doing _table1.Rows.Count to see if a datatable has any rows. Is there any classes and functions in C# that just gives me if there are any rows. I don't need the data of the rows. Just the count is what I need. I'm running this query against very large datasets so I don't wanna fill the datatable with all the row info.

like image 926
iefpw Avatar asked Dec 04 '22 16:12

iefpw


2 Answers

string myScalarQuery = "select count(*) from TableName";

SqlCommand myCommand = new SqlCommand(myScalarQuery, myConnection);
myCommand.Connection.Open();
int count = (int) myCommand.ExecuteScalar();
myConnection.Close();

Possible optimization of the query per the comments bellow: Select Top 1 * FROM TableName

like image 80
TGH Avatar answered Dec 10 '22 10:12

TGH


The least expensive way is using SqlDataReader's HasRows property
UPDATE: of course, the most efficient SELECT query will be like "Select Top 1 1 FROM TableName", which doesn't even need to pull any column data.

using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (SqlDataReader rdr = cmd.ExecuteReader())
    {
        if (rdr.HasRows)
            ...
    }
}
like image 32
detale Avatar answered Dec 10 '22 11:12

detale