Pessimistic lock in T-SQL

前端 未结 3 644
一向
一向 2020-12-20 22:43

If i SELECT a row for updating in MS SQL Server, and want to have it locked till i either update or cancel, which option is better :-

1) Use a query hint like UPDLOC

3条回答
  •  鱼传尺愫
    2020-12-20 23:28

    If you're waiting on another resource such as an end-user, then take Dave Markle's advice and don't do it.

    Otherwise, try the following T-SQL code:

    BEGIN TRAN
    
    SELECT *
    FROM   authors AU
    WITH   (HOLDLOCK, ROWLOCK)
    WHERE  AU.au_id = '274-80-9391'
    
    /* Do all your stuff here while the row is locked */
    
    COMMIT TRAN
    

    The HOLDLOCK hint politely asks SQL Server to hold the lock until you commit the transaction. The ROWLOCK hint politely asks SQL Server to lock only this row rather than issuing a page or table lock.

    Be aware that if lots of rows are affected, either SQL Server will take the initiative and escalate to page locks, or you'll have a whole army of row locks filling your server's memory and bogging down processing.

提交回复
热议问题