SQL Server 临时表与游标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4568464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 08:44:05  来源:igfitidea点击:

SQL server temporary tables vs cursors

sqlstored-procedurestemp-tables

提问by SARAVAN

In SQL Server stored procedures when to use temporary tables and when to use cursors. which is the best option performance wise?

在 SQL Server 存储过程中何时使用临时表以及何时使用游标。哪个是最好的选择性能明智的?

采纳答案by marc_s

If ever possible avoidcursors 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.

如果可能的话,避免像瘟疫一样的光标。SQL Server 是基于集合的- 您需要以 RBAR(逐行痛苦)方式执行的任何操作都将缓慢、缓慢并且违背 SQL 工作原理的基本原则。

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, INSERTand joins - don't force your procedural thinking onto SQL Server - that's not the best way to go.

您的问题非常模糊 - 根据该信息,我们无法真正确定您要做什么。但主要建议仍然是:只要有可能(并且在绝大多数情况下都是可能的),使用基于集合的操作- SELECT, UPDATE, INSERT和连接——不要将你的过程思维强加于 SQL Server——这不是最好的方法。

So if you can use set-based operations to fill and use your temporary tables, I would prefer that method over cursors every time.

因此,如果您可以使用基于集合的操作来填充和使用您的临时表,那么我每次都更喜欢这种方法而不是游标。

回答by HLGEM

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

建议你阅读这个:http: //wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them