Which lock hints should I use (T-SQL)?

后端 未结 5 934
暖寄归人
暖寄归人 2020-12-13 20:45

I want to implement an atomic transaction like the following:

BEGIN TRAN A

SELECT id
FROM Inventory
WITH (???)
WHERE material_id = 25 AND quantity > 10

         


        
5条回答
  •  我在风中等你
    2020-12-13 21:13

    table hints

    WITH (HOLDLOCK) allows other readers. UPDLOCK as suggested elsewhere is exclusive.

    HOLDLOCK will prevent other updates but they may use the data that is updated later.

    UPDLOCK will prevent anyone reading the data until you commit or rollback.

    Have you looked at sp_getapplock? This would allow you to serialise this code (if it's the only update bit) without UPDLOCK blocking

    Edit: The problem lies mainly in this code running in 2 different sessions. With HOLDLOCk or REPEATABLE_READ, the data will be read in the 2nd session before the 1st session update. With UPDLOCK, noone can read the data in any session.

提交回复
热议问题