SELECT FOR UPDATE with SQL Server

后端 未结 18 2247
自闭症患者
自闭症患者 2020-11-27 11:49

I\'m using a Microsoft SQL Server 2005 database with isolation level READ_COMMITTED and READ_COMMITTED_SNAPSHOT=ON.

Now I want to use:

18条回答
  •  借酒劲吻你
    2020-11-27 12:39

    I'm assuming you don't want any other session to be able to read the row while this specific query is running...

    Wrapping your SELECT in a transaction while using WITH (XLOCK,READPAST) locking hint will get the results you want. Just make sure those other concurrent reads are NOT using WITH (NOLOCK). READPAST allows other sessions to perform the same SELECT but on other rows.

    BEGIN TRAN
      SELECT *
      FROM  WITH (XLOCK,READPAST) 
      WHERE RowId = @SomeId
    
      -- Do SOMETHING
    
      UPDATE 
      SET =@somevalue
      WHERE RowId=@SomeId
    COMMIT
    

提交回复
热议问题