Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

database - SQL Server - updlock, serializable doesn't block 100%

I have a stored procedure where my code basically inserts a record if the ids don't exist in the table, all wrapped in a transaction called from app which also uses a transaction scope.

The stored procedure code snippet looks like:

begin transaction

set @exist = (select top 1 id from table with (updlock, serializable)  
              where uid = @uid and gid = @gid)

-- if doesn't exist... insert
commit transaction

For more background, there are multiple servers calling this exact stored procedure.

I have read multiple resources and they all seem to point out that using (updlock, serializable) should ensure blocking, similar to this Why does my SQL Server UPSERT code sometimes not block?

Some where also mentioned that if the query plans are different, the resources locked could be different but surely this shouldn't apply to my case as it is identical in table, parameters, query etc..

But I have noticed there are duplicate records inside the table (not a lot), so my question is are there gaps in my knowledge about the usage of updlock and what could be causing this behaviour?

question from:https://stackoverflow.com/questions/65948932/sql-server-updlock-serializable-doesnt-block-100

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To confirm this you should run an Extended Events session and capture the actual locks taken when the procedure is called. It seems likely that the locks are only being taken at the row level and looking at the definition of HOLDLOCK states it is only for the statement.

You may either need to include a TABLOCK or consider setting the TRANSACTION ISOLATION LEVEL to SERIALIZABLE for the transaction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...