SQL Server中游标的用途是什么? [英] What is the use of a cursor in SQL Server?

查看:122
本文介绍了SQL Server中游标的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用数据库游标;首先,我需要了解它的用法和语法,以及在哪种情况下可以在存储过程中使用它?不同版本的SQL Server是否有不同的语法?



何时需要使用?

解决方案方案

游标是一种机制,用于显式枚举结果集的行,而不是像这样检索它。



但是,尽管它们可能对于习惯于编写而不是RS.EOF做... 的程序员来说,使用起来更舒适,但如果可能的话,在SQL Server存储过程中通常应该避免使用它们-如果您不使用游标就可以编写查询,则可以为优化器提供更好的机会来找到实现该查询的快速方法。



老实说,除了一些管理任务(例如循环遍历目录中的所有索引并重建它们)外,我从未发现无法避免的现实使用案例。我想它们可能在报表生成或邮件合并中有一些用途,但是在与数据库进行对话的应用程序中执行类似游标的工作可能更有效,让数据库引擎可以做最好的事情-设置操作。 / p>

I want to use a database cursor; first I need to understand what its use and syntax are, and in which scenario we can use this in stored procedures? Are there different syntaxes for different versions of SQL Server?

When is it necessary to use?

解决方案

Cursors are a mechanism to explicitly enumerate through the rows of a result set, rather than retrieving it as such.

However, while they may be more comfortable to use for programmers accustomed to writing While Not RS.EOF Do ..., they are typically a thing to be avoided within SQL Server stored procedures if at all possible -- if you can write a query without the use of cursors, you give the optimizer a much better chance to find a fast way to implement it.

In all honesty, I've never found a realistic use case for a cursor that couldn't be avoided, with the exception of a few administrative tasks such as looping over all indexes in the catalog and rebuilding them. I suppose they might have some uses in report generation or mail merges, but it's probably more efficient to do the cursor-like work in an application that talks to the database, letting the database engine do what it does best -- set manipulation.

这篇关于SQL Server中游标的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆