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

后端 未结 5 924
暖寄归人
暖寄归人 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:11

    You may actually be better off setting the transaction isolation level rather than using a query hint.

    The following reference from Books Online provides details of each of the different Isolation levels.

    http://msdn.microsoft.com/en-us/library/ms173763.aspx

    Here is good article that explains the various types of locking behaviour in SQL Server and provides examples too.

    http://www.sqlteam.com/article/introduction-to-locking-in-sql-server

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 21:15

    MSSQL:

    SELECT id
    FROM Inventory (UPDLOCK)
    WHERE material_id = 25 AND quantity > 10;
    
    http://www.devx.com/tips/Tip/13134
    



    By any chance you're interested with PostgreSQL:

    SELECT id
    FROM Inventory    
    WHERE material_id = 25 AND quantity > 10
    FOR UPDATE;
    
    0 讨论(0)
  • 2020-12-13 21:25

    Lock hints:

    WITH (UPDLOCK, HOLDLOCK)
    
    0 讨论(0)
  • 2020-12-13 21:26

    I believe this would be UPDLOCK.

    http://www.devx.com/tips/Tip/13134

    0 讨论(0)
提交回复
热议问题