游标sql server
介绍 (Introduction)
在上一篇文章中,我们讨论了如何设置基本游标。 我们解释了游标是基于行的操作,它采用给定的SELECT语句并将数据处理分解为循环执行。 没有数据库管理背景或在学习时不喜欢数据库类的人通常会发现SQL Server游标很方便并且编写起来很有趣。 这是因为它们摆脱了编写大多数T-SQL脚本时常见的基于集合的逻辑的束缚。 出于这个原因,我们经常发现写入应用程序业务逻辑SQL Server游标,这实在令人遗憾,因为它们是真正的性能消耗。 是的,有时候可以使用游标,可以通过使用其不同的类型对其进行微调,但是,根据一般经验,应该不惜一切代价避免使用游标。性能问题 (Performance problems)
SQL Server cursors are notoriously bad for performance. In any good development environment people will talk about cursors as if they were demons to be avoided at all costs. The reason for this is plain and simple; they are the best way to slow down an application. This is because SQL Server, like any good relational database management system (RDBMS), is optimized for set-based operations. Take this simple SELECT statement as an example:
众所周知,SQL Server游标会降低性能。 在任何良好的开发环境中,人们都会谈论游标,就好像不惜一切代价避免游标一样。 原因很简单。 它们是减慢应用程序速度的最佳方法。 这是因为SQL Server与任何良好的关系数据库管理系统(RDBMS)一样,都针对基于集合的操作进行了优化。 以这个简单的SELECT语句为例:
SELECT *
FROM AdventureWorks2012.Sales.SalesOrderDetail
WHERE ModifiedDate BETWEEN '2008-07-15 00:00:00.000' AND '2008-07-31 00:00:00.000'
When you write a SELECT statement like this (that returns 1051 rows) to fetch a bunch of data from that database the system receives the statement and creates or uses an existing query plan, then it uses indexes to locate the data on the disk, fetches the data in one foul swoop and returns the data as a set. If your indexes are correctly placed the query can be sped up. In the case above if the ModifiedDate field was included in an index it would run faster.
当您编写这样的SELECT语句(返回1051行)以从该数据库中获取一堆数据时,系统会接收该语句并创建或使用现有的查询计划,然后使用索引在磁盘上定位数