如何编写SQL来更新并消除死锁?
我需要非常频繁地执行这个SQL,
UPDATE Users SET UserPoint=UserPoint+(@UserPoint) WHERE UserID=@UserID
我可以允许脏读或脏写,但我不想看到死锁,有没有办法最大程度地避免死锁?
编辑
好的,@Tomtome 这可能不是僵局,这对我来说是个好消息。
这里我跟进一个新问题,希望对你有所帮助。
我还需要读取数据,所以我用的
SELECT UserPoint FROM [Users] WITH (NOLOCK) WHERE UserID=@UserID
不是事务,只是简单的一行SQL,而且我已经使用了nolock
,是否还需要使用SET TRANSACTION ISOLATION LEVEL< /code> 以避免死锁,如果我允许脏读。
再次EIDT
我认为将隔离级别设置为读取未提交和使用NOLOCK是同一件事。这样就完成了。 谢谢大家,
I need to perform this SQL very frequently
UPDATE Users SET UserPoint=UserPoint+(@UserPoint) WHERE UserID=@UserID
I can allow dirty-read or dirty-write but I do not want to see deadlock, is there a way to max the chance to avoid deadlock?
EDIT
OK, @Tomtome this might not be a deadlock, thats good news for me.
Here I follow up a new question, hope you can help.
I also need to read the data, so I use
SELECT UserPoint FROM [Users] WITH (NOLOCK) WHERE UserID=@UserID
It's not a transaction, just a simple one line SQL, and I already use the nolock
, do I need to use SET TRANSACTION ISOLATION LEVEL
to avoid deadlock, if I allow dirty-read.
EIDT AGAIN
I think SET ISOLATION LEVEL to READ UNCOMMITTED and WITH NOLOCK are same thing. so Done.
Thanks everyone,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,因为这个语句不能死锁。
死锁至少需要持有两个锁(a 和 b)。因此,一个进程获取锁 A,等待 B,另一个进程获取 B,等待 A - 等待无法解决任何问题。如果上面的语句遇到锁,它将等待(并且可能超时),但不会死锁。
除非它是具有更多语句的较大事务的一部分。
所以,这个问题一开始就不存在;)
No, because this statement CAN NOT DEADLOCK.
A Deadlock requires two locks to be hold (a and b) as minimum. So one process gets lock A, waits for B, another gets B, waits for A - and nothing can be resolved by waiting. If the above statement encounters a lock it will wait (and possibly timeout), but not deadlock.
UNLESS it is part of a larger transaction with more statements.
So, the problem does not exist to start with ;)