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.
Add a comment
|
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
8 Comments
TGH
My understanding is that you want a query to determine if a table contains any rows? So why not just run a count query
user1166147
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.
TGH
@user1166147 I agree. I included the count just for the flexibility if the count is needed
TGH
Added your optimization suggestion @user1166147
|
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
TGH
The slowest component will always be the query itself, so the C# part is imo less important.