简体   繁体   English

如何获取SQL Server中的写锁?

[英]How do I acquire write locks in SQL Server?

I need to run a query that selects ten records. 我需要运行一个查询,选择十条记录。 Then, based on their values and some outside information, update said records. 然后,根据它们的值和一些外部信息,更新所述记录。

Unfortunately I am running into deadlocks when I do this in a multi-threaded fashion. 不幸的是,当我以多线程方式执行此操作时,就会陷入僵局。 Both threads A and B run their selects at the same time, acquiring read locks on the ten records. 线程A和B同时运行它们的选择,从而获得了十条记录的读取锁。 So when one of them tries to do an update, the other transaction is aborted. 因此,当其中一个尝试进行更新时,另一个事务将中止。

So what I need to be able to say is "select and write-lock these ten records". 因此,我需要说的是“选择并写入锁定这十条记录”。

(Yea, I know serial transactions should be avoided, but this is a special case for me.) (是的,我知道应该避免串行事务,但这对我来说是一种特殊情况。)

Try applying UPDLOCK 尝试应用UPDLOCK

BEGIN TRAN

SELECT * FROM table1
WITH (UPDLOCK, ROWLOCK)
WHERE col1 = 'value1'

UPDATE table1 
set col1 = 'value2'
where col1 = 'value1'

COMMIT TRAN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM