简体   繁体   中英

SQL Server locking for an UPDATE with WHERE clause and sub-SELECT

It seems that this topic is asked often, and I think I found an answer to my original question, but now I'm curious about a difference between that (and a few other answers I found) and my SQL:

update Foos set Owner = 'me' OUTPUT INSERTED.id where Owner is null and id in
  (select top 1 id from Foos where Owner is null)

I now understand that my original hypothesis is correct regarding the sub-select and concurrency, where a concurrent thread may select the same id as another thread is about to update that id. However, does my where clause in the update piece help prevent this race condition (in read committed level)?

My theory is that, while two threads may get the same id from the sub- select , only one would be able to update , because the update is atomic and includes the condition. The other thread would fail, or update zero records. Is that true?

Try this

;WITH CTE AS 
 (
  SELECT ID, [Owner] 
     , ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) rn 
  FROM Foos
  WHERE [Owner] IS NULL
 ) 
update CTE 
  SET [Owner] = 'me' 
OUTPUT INSERTED.id 
WHERE rn = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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