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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With