SQL 使用while循环与Cursor是最佳实践吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34776618/
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 04:20:25  来源:igfitidea点击:

is it a best practice to use while loop vs Cursor?

sqlsql-server

提问by Bikkar

what criteria should we keep in mind while choosing which of the above options when there's a need to loop through table/data.

当需要循环遍历表/数据时,我们在选择上述哪些选项时应该记住什么标准。

回答by Adamantish

WHILE loop and cursor perform similarly poorly.

WHILE 循环和游标的性能同样不佳。

Seeing as you're using SQL you're probably going to execute some SQL commands inside the loop. The DB engine is geared toward getting a lot done in batch with one SQL command. Having a loop fire thousands of tiny ones won't actually be tiny. The overheads for each one are too hefty.

当您使用 SQL 时,您可能会在循环内执行一些 SQL 命令。数据库引擎旨在通过一个 SQL 命令批量完成大量工作。有一个循环触发成千上万个微小的实际上不会很小。每个人的开销都太大了。

Most things you might first think to do with a cursor or loop can be done another way in SQL though they may require you work out what temporary tables you're going to make to help out.

您可能首先想到用游标或循环做的大多数事情可以在 SQL 中以另一种方式完成,尽管它们可能需要您计算出您将要制作的临时表来提供帮助。

This is helpful: How to think in SQL?

这很有帮助:如何在 SQL 中思考?