SQL Cursors…Any use cases you would defend?

后端 未结 10 693
萌比男神i
萌比男神i 2021-01-06 23:01

I\'ll go first.

I\'m 100% in the set-operations camp. But what happens when the set logic on the entire desired input domain leads to a such a large retrieval that

10条回答
  •  时光取名叫无心
    2021-01-06 23:38

    Sure, there are a number of places where cursors might be better than set-based operations.

    One is if you're updating a lot of data in a table (for example a SQL Agent job to pre-compute data on a schedule) then you might use cursors to do it in multiple small sets rather than one large one to reduce the amount of concurrent locking and thus reduce the chance of lock contention and/or deadlocks with other processes accessing the data.

    Another is if you want to take application-level locks using the sp_getapplock stored procedure, which is useful when you want to ensure rows that are being polled for by multiple processes are retrieved exactly once (example here).

    In general though, I'd agree that it's best to start using set based operations if possible, and only move to cursors if required either for functionality or performance reasons (with evidence to back the latter up).

提交回复
热议问题