Cursor verus while loop - what are the advantages/disadvantages of cursors?

后端 未结 4 671
独厮守ぢ
独厮守ぢ 2020-12-17 09:40

Is it a good idea to use while loop instead of a cursor? What are the advantages/disadvantages of cursors?

相关标签:
4条回答
  • 2020-12-17 10:20

    Some of these depends on the DBMS, but generally:

    Pros:

    • Outperform loops when it comes to row-by-row processing

    • Works reasonably well with large datasets

    Cons:

    • Don't scale as well

    • Use more server resources

    • Increases load on tempdb

    • Can cause leaks if used incorrectly (eg. Open without corresponding Close)

    0 讨论(0)
  • 2020-12-17 10:20

    Some disadvantages of cursors are here

    Then there is also this (Actually a very interesting problem called - "Halloween problem")

    0 讨论(0)
  • 2020-12-17 10:22

    I'm following this bit of advice:

    [...] which is better: cursors or WHILE loops? Again, it really depends on your situation. I almost always use a cursor to loop through records when necessary. The cursor format is a little more intuitive for me and, since I just use the constructs to loop through the result set once, it makes sense to use the FAST_FORWARD cursor. Remember that the type of cursor you use will have a huge impact on the performance of your looping construct.

    — Tim Chapman in Comparing cursor vs. WHILE loop performance in SQL Server 2008

    The linked article contains simple examples of how to implement each approach.

    0 讨论(0)
  • 2020-12-17 10:22

    I would ask you what you are doing with that cursor/while loop.

    If you are updating or returning data why don't you use a proper WHERE clause. I know people who would say you should never use cursors.

    0 讨论(0)
提交回复
热议问题