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. 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.
最佳回答
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
问题回答
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) ... } }




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签