且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在 SQL Server 中使用游标被认为是不好的做法?

更新时间:2022-11-16 12:54:54

因为游标占用内存并创建锁.

Because cursors take up memory and create locks.

您真正在做的是试图将基于集合的技术强制转换为非基于集合的功能.而且,平心而论,我应该指出游标确实有用,但他们不赞成,因为许多不习惯使用基于集合的解决方案的人使用游标而不是弄清楚集合基于解决方案.

What you are really doing is attempting to force set-based technology into non-set based functionality. And, in all fairness, I should point out that cursors do have a use, but they are frowned upon because many folks who are not used to using set-based solutions use cursors instead of figuring out the set-based solution.

但是,当您打开游标时,您基本上是将这些行加载到内存中并锁定它们,从而创建潜在的块.然后,当您在游标中循环时,您正在对其他表进行更改,并且仍然保持游标的所有内存和锁处于打开状态.

But, when you open a cursor, you are basically loading those rows into memory and locking them, creating potential blocks. Then, as you cycle through the cursor, you are making changes to other tables and still keeping all of the memory and locks of the cursor open.

所有这些都有可能导致其他用户出现性能问题.

All of which has the potential to cause performance issues for other users.

因此,作为一般规则,游标是不受欢迎的.特别是如果这是解决问题的第一个解决方案.

So, as a general rule, cursors are frowned upon. Especially if that's the first solution arrived at in solving a problem.