CTE例子证明它比Cursor更好
我读到 CTE 比光标更好。但我无法找到可以证明这一点的简单清晰的例子。我是 Sql Server 2005 的新手,为了理解它,我需要一个简单的示例,在该示例中我们通过 CTE 存储值并一一处理它。
I have read that CTE are better than cursor. But I am unable to find the simple clear example which can prove this. I am newbie in Sql Server 2005 and to understand it I need a simple example in which we are storing value via CTE and processing it one by one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用游标,则行序列将被逐一执行,因为它一次仅获取一行。因此,当我们在行数较多的表中使用 Cursor 时,会花费更多的时间。
If you use Cursor, the sequence of rows are get executed one by one because it fetch only one row at a time. So it takes more time when we use Cursor in tables which has more rows.
CTE 在递归场景中产生更快的结果。 CTE的结果被重复使用以获得最终结果集。因此,既然您已经在 CTE 中使用了 where 子句或子查询,那么它肯定会显示出性能的改进。虽然游标的执行流程是同步的(逐一执行),但势必会花费更多时间。
参考:http://msdn.microsoft.com/ en-us/library/ms190766(v=sql.105).aspx
请注意,在许多情况下,临时表比 CTE 提供更好的性能,因此您也应该尝试使用临时表。< br>
参考: http://social.msdn .microsoft.com/Forums/en/transactsql/thread/d040d19d-016e-4a21-bf44-a0359fb3c7fb
CTE yields a faster result in a recursive scenario. The result of CTE is repeatedly used to get the final resultset. So since you have taken your where clause or subquery in CTE, definitely it is going to show performance improvement. While cursors flow of execution is synchronous(it executes one by one), it is bound to take more time.
Reference : http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx
Just a note, in many scenarios, temp tables gives better performance then CTE also, so you should give a try to temp tables as well.
Reference : http://social.msdn.microsoft.com/Forums/en/transactsql/thread/d040d19d-016e-4a21-bf44-a0359fb3c7fb