How to exclusively lock a row that prevent CRUD operation

前端 未结 5 1919
無奈伤痛
無奈伤痛 2021-01-11 15:56

Hi expert how I can lock a row in sql server that prevent CRUD operation even SELECT. Is it Possible? Serializable Isolation level does not prevent SELECT. thanks

5条回答
  •  Happy的楠姐
    2021-01-11 16:24

    BEGIN TRAN
    
        SELECT 1
        FROM Table
        WITH (XLOCK, ROWLOCK)
    
    COMMIT TRAN
    

    That will do the trick.

    EDIT

    As noted by others, you cannot lock a row to not be read. The only way I know of doing this is as follows:

    WITH (UPDLOCK, TABLOCK)
    

    And this is assuming that a WITH (NOLOCK) is never used in a SELECT statement (which should be avoided anyway).

    I tested this and it will work, although TABLOCK should only be used in extreme cases. Certainly if concurrency is required, it's a bad solution and some other form of locking would be needed. One way is to update a bit column "Available True/False" and only read rows where Available = True. As @gbn suggested, READPAST could be used with this.

提交回复
热议问题