Pros and cons of using a cursor (in SQL server)

前端 未结 5 1667
太阳男子
太阳男子 2021-02-15 17:07

I asked a question here Using cursor in OLTP databases (SQL server)

where people responded saying cursors should never be used.

I feel cursors are very powerful

5条回答
  •  自闭症患者
    2021-02-15 17:38

    I had always disliked cursors because of their slow performance. However, I found I didn't fully understand the different types of cursors and that in certain instances, cursors are a viable solution.

    When you have a business problem that can only be solved by processing one row at a time, then a cursor is appropriate.

    So to improve performance with the cursor, change the type of cursor you are using. Something I didn't know was, if you don't specify which type of cursor you are declaring, you get the Dynamic Optimistic type by default, which is the one that is the slowest for performance because it's doing lots of work under the hood. However, by declaring your cursor as a different type, say a static cursor, it has very good performance.

    See these articles for a fuller explanation:

    The Truth About Cursors: Part I

    The Truth About Cursors: Part II

    The Truth About Cursors: Part III

    I think the biggest con against cursors is performance, however, not laying out a task in a set based approach would probably rank second. Third would be readability and layout of the tasks as they usually don't have a lot of helpful comments.

    SQL Server is optimized to run the set based approach. You write the query to return a result set of data, like a join on tables for example, but the SQL Server execution engine determines which join to use: Merge Join, Nested Loop Join, or Hash Join. SQL Server determines the best possible joining algorithm based upon the participating columns, data volume, indexing structure, and the set of values in the participating columns. So using a set based approach is generally the best approach in performance over the procedural cursor approach.

提交回复
热议问题