简体   繁体   English

使用SqlCommand.ExecuteScalar()时是否需要放置前1

[英]Do I need to put top 1 when using SqlCommand.ExecuteScalar()

I've analyzed the code of SqlCommand and see that it works fine (see CompleteExecuteScalar method). 我已经分析 SqlCommand 的代码并看到它工作正常(请参阅CompleteExecuteScalar方法)。 But I'm not sure should I use top 1 in the query. 但我不确定我应该在查询中使用top 1 For example I have select name from Person and table Person contains a lot of records. 例如,我select name from PersonPerson包含很多记录。 Should I modify qry to select top 1 name from Person ? 我应该修改qry select top 1 name from Person吗? Or I can leave qry as is and it will not affect performance/memory etc? 或者我可以保持qry原样,它不会影响性能/内存等? I'm afraid that server can buffer some data before output. 我担心服务器可以在输出之前缓冲一些数据。

You should definitely put TOP 1 in the query if you want to fetch only one row from the database, regardless of whether you are delivering the data through ExecuteScalar or ExecuteReader for instance. 如果您只想从数据库中获取一行,则无论您是通过ExecuteScalar还是ExecuteReader传送数据,都应该在查询中放置TOP 1

You should not read source code to come to such conclusion. 你不应该阅读源代码来得出这样的结论。 In fact, the way command is implemented is subject to encapsulation and calling classes should not make decisions based on exact implementation of the command. 实际上,实现方式命令受封装限制,调用类不应基于命令的确切实现做出决策。

Instead, my thinking is that the database is scarce resource that should be used optimally in terms of data throughput and related measures. 相反,我的想法是数据库是稀缺资源,应该在数据吞吐量和相关措施方面得到最佳利用。 That includes indicating to the database that exactly one row is wanted and be done with it. 这包括向数据库指示只需要一行并完成它。 Let lower layers, such as command implementation and database itself see how to use that information for the best performance. 让较低层(如命令实现和数据库本身)了解如何使用该信息以获得最佳性能。

ExecuteScalar fetches the first column value of the first row. ExecuteScalar获取第一行的第一列值。 So, it won't make a difference if you add TOP 1 to your query or not. 因此,如果您将TOP 1添加到查询中,它将没有任何区别。 However, it is recommended that TOP 1 be added if you are expecting duplicate values and you need that one particular value (for the sake of speed). 但是,如果您希望重复值并且需要一个特定值(为了速度),建议添加TOP 1 One such plausible scenario is that you are reusing some script that returns a set or rows containing Customer Information about a specific customer, provided, your first column is the CustomerID or any primary key. 一个这样合理的场景是,您正在重用一些脚本,该脚本返回一组或多行,其中包含有关特定客户的客户信息,前提是您的第一列是CustomerID或任何主键。

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

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