T-SQL 中的悲观锁

发布于 2024-07-10 12:30:35 字数 156 浏览 6 评论 0原文

如果我在 MS SQL Server 中选择一行进行更新,并希望将其锁定直到更新或取消,哪个选项更好:-

1)使用像 UPDLOCK 这样的查询提示 2)对事务使用REPEATABLE READ隔离级别 3) 任何其他选项。

谢谢, 查克。

If i SELECT a row for updating in MS SQL Server, and want to have it locked till i either update or cancel, which option is better :-

1) Use a query hint like UPDLOCK
2) Use REPEATABLE READ isolation level for the transaction
3) any other option.

Thanks,
Chak.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

ぃ双果 2024-07-17 12:30:35

如果您正在等待其他资源(例如最终用户),那么请采纳戴夫·马克尔的建议,不要这样做。

否则,请尝试以下 T-SQL 代码:

BEGIN TRAN

SELECT *
FROM   authors AU
WITH   (HOLDLOCK, ROWLOCK)
WHERE  AU.au_id = '274-80-9391'

/* Do all your stuff here while the row is locked */

COMMIT TRAN

HOLDLOCK 提示礼貌地要求 SQL Server 保持锁定,直到您提交事务。 ROWLOCK 提示礼貌地要求 SQL Server 仅锁定该行,而不是发出页锁或表锁。

请注意,如果大量行受到影响,SQL Server 要么会采取主动并升级为页锁,要么您将有一整群行锁填满服务器的内存并导致处理陷入困境。

If you're waiting on another resource such as an end-user, then take Dave Markle's advice and don't do it.

Otherwise, try the following T-SQL code:

BEGIN TRAN

SELECT *
FROM   authors AU
WITH   (HOLDLOCK, ROWLOCK)
WHERE  AU.au_id = '274-80-9391'

/* Do all your stuff here while the row is locked */

COMMIT TRAN

The HOLDLOCK hint politely asks SQL Server to hold the lock until you commit the transaction. The ROWLOCK hint politely asks SQL Server to lock only this row rather than issuing a page or table lock.

Be aware that if lots of rows are affected, either SQL Server will take the initiative and escalate to page locks, or you'll have a whole army of row locks filling your server's memory and bogging down processing.

酒废 2024-07-17 12:30:35

两者都不。 您几乎不想在用户输入数据时保持事务打开。 如果您必须实现这样的悲观锁,人们通常会通过滚动自己的功能来实现。

考虑一下你正在做的事情的全部后果。 我曾经开发过一个像这样实现锁定的系统。 您经常会遇到大量陈旧的锁,当您将其强加给用户时,他们很快就会感到困惑和愤怒。 在我们的案例中,我们的解决方案是完全删除此锁定功能。

Neither. You almost never want to hold a transaction open while your user is inputting data. If you have to implement a pessimistic lock like this, people generally do it by rolling their own functionality.

Consider the full ramifications of what you are doing. I once worked on a system that implemented locking like this. You often run into tons of stale locks, and your users get confused and angry very quickly when you foist this on them. The solution for us in our case was to remove this locking functionality entirely.

沧笙踏歌 2024-07-17 12:30:35

请注意,尽管使用 ROWLOCK,SQL Server 可能会选择在其认为需要的情况下仍采用整页锁定。

just note that despite using ROWLOCK SQL Server might choose to still take a full page lock if it deems needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文