Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclusively lock a row that prevent CRUD operation

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

like image 721
Arian Avatar asked Jan 04 '11 18:01

Arian


Video Answer


1 Answers

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.

like image 99
IamIC Avatar answered Oct 15 '22 16:10

IamIC