简体   繁体   English

C#SQL如果查询返回任何行计数

[英]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. 我正在使用DataTablesqlAdapter.Fill(_table1) ,然后执行_table1.Rows.Count以查看数据表是否有任何行。 Is there any classes and functions in C# that just gives me if there are any rows. 如果有任何行,C#中是否有任何类和函数可以提供给我。 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. 我正在针对非常大的数据集运行此查询,因此我不想用所有行信息填充数据表。

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 根据以下注释可能优化查询:选择Top 1 * FROM TableName

The least expensive way is using SqlDataReader's HasRows property 最便宜的方法是使用SqlDataReader的HasRows属性
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. 更新 :当然,最有效的SELECT查询将类似于“选择Top 1 1 FROM TableName”,甚至不需要提取任何列数据。

using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (SqlDataReader rdr = cmd.ExecuteReader())
    {
        if (rdr.HasRows)
            ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM