How to exclusively lock a table in MS SQL

Start a transaction and select from the table using the (TABLOCKX) hint.

As the result, read from this table outside of the transaction will be queued until the transaction is committed or rolled back.

1
2
3
4
5
6
7
8
BEGIN TRAN  
 
SELECT    * 
FROM      Table1 (TABLOCKX)    
 
WAITFOR DELAY '00:00:30'    
 
ROLLBACK TRAN
BEGIN TRAN  

SELECT    * 
FROM      Table1 (TABLOCKX)    

WAITFOR DELAY '00:00:30'    

ROLLBACK TRAN

Leave a comment

Your email address will not be published. Required fields are marked *