C# SQL if 查询返回任何行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10762639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# SQL if query returns any rows count
提问by iefpw
What is the simplest and most efficient way to find if a data returns using a query? I'm using DataTablelike sqlAdapter.Fill(_table1)and then doing _table1.Rows.Countto 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.
使用查询查找数据是否返回的最简单和最有效的方法是什么?我正在使用DataTablelikesqlAdapter.Fill(_table1)然后 do_table1.Rows.Count来查看数据表是否有任何行。C# 中是否有任何类和函数只给我是否有任何行。我不需要行的数据。只是计数是我需要的。我正在针对非常大的数据集运行此查询,因此我不想用所有行信息填充数据表。
采纳答案by TGH
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
根据下面的评论可能优化查询: Select Top 1 * FROM TableName
回答by detale
The least expensive way is using SqlDataReader's HasRowsproperty
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.
最便宜的方法是使用 SqlDataReader 的HasRows属性
UPDATE:当然,最有效的 SELECT 查询将类似于“Select Top 1 1 FROM TableName”,它甚至不需要提取任何列数据。
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
...
}
}

