4

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.

0

2 Answers 2

9
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

Sign up to request clarification or add additional context in comments.

8 Comments

My understanding is that you want a query to determine if a table contains any rows? So why not just run a count query
Looks good to me (+1). Well, except not being a statically-typed query ;-) However, ExecuteScalar has an object return type so a Convert.ToInt32 might be in order.
If you just want to see rows and don't actually need the count maybe SELECT TOP 1 1 FROM instead of * - to stop processing as soon as it sees a row.
@user1166147 I agree. I included the count just for the flexibility if the count is needed
Added your optimization suggestion @user1166147
|
8

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)
            ...
    }
}

2 Comments

What would the SqlCommand look like in this case (for completeness)? Is there as reason to favor this over a COUNT?
The slowest component will always be the query itself, so the C# part is imo less important.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.