SQL Server 临时表与游标
在 SQL Server 存储过程中何时使用临时表以及何时使用游标。哪个是性能方面最好的选择?
In SQL Server stored procedures when to use temporary tables and when to use cursors. which is the best option performance wise?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果可能的话,像瘟疫一样避免光标。 SQL Server 是基于集合的 - 您需要以 RBAR(逐行)方式执行的任何操作都会很慢、迟缓,并且违背 SQL 工作原理的基本原则。
您的问题非常模糊 - 根据该信息,我们无法真正判断您想要做什么。但主要建议仍然是:只要有可能(并且在绝大多数情况下都是可能的),请使用基于集合的操作 - SELECT、UPDATE、INSERT 和联接 - 不要将程序思维强加于 SQL服务器 - 这不是最好的方法。
因此,如果您可以使用基于集合的操作来填充和使用临时表,我每次都会更喜欢该方法而不是游标。
If ever possible avoid cursors like the plague. SQL Server is set-based - anything you need to do in an RBAR (row-by-agonizing-row) fashion will be slow, sluggish and goes against the basic principles of how SQL works.
Your question is very vague - based on that information, we cannot really tell what you're trying to do. But the main recommendation remains: whenever possible (and it's possible in the vast majority of cases), use set-based operations
- SELECT, UPDATE, INSERT
and joins - don't force your procedural thinking onto SQL Server - that's not the best way to go.So if you can use set-based operations to fill and use your temporary tables, I would prefer that method over cursors every time.
游标是逐行工作的,并且性能极差。在几乎所有情况下,它们都可以被更好的基于集合的代码替换(尽管通常不是临时表)。
临时表可能好也可能坏,具体取决于数据量以及您对它们的处理方式。它们通常不能替代游标。
建议你读一下这篇:
http://wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them
Cursors work row-by-row and are extremely poor performers. They can in almost all cases be replaced by better set-based code (not normally temp tables though)
Temp tables can be fine or bad depending on the data amount and what you are doing with them. They are not generally a replacement for a cursor.
Suggest you read this:
http://wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them
我相信 SARAVAN 最初对游标和临时表进行了比较,因为很多时候您会遇到这样一种情况:使用带有标识列的临时表和 @counter 变量可用于滚动/导航数据集,就像在一个光标。
根据我的经验,使用临时表(或表变量)场景可以帮助我完成 95% 的工作,并且比通常较慢的游标更快。
I believe SARAVAN originally made the comparison between cursors and temp tables because many times you are confronted with a situation where using a temp table with an identity column and a @counter variable can be used to scroll/navigate through a data set much like one in a cursor.
In my experience, using the temp table (or table variable) scenario can help me get the job done 95% of the time and is faster than the typically slow cursor.