I want to lock a table when a store procedure is executing.
Would this be a good way?
CREATE PROCEDUE sp_test
@tableName nvarchar(128)
AS
DECLARE @sql nvarchar(MAX) = 'SELECT * FROM ' + @tableName + 'WITH TABLOCK'
EXEC @sql
-- DO my operations
-- How Do I release the lock? or does it get release when the execution is done
Or is there a better way to achieve this.
Thanks
You could take specific locks out on the table at the beginning of the procedure call.
If you wanted to prevent data modification to the table you could take an IX lock.
If you wanted to prevent any other process from accessing the data you could take an X lock. Of course this doesn’t prevent any uncommitted reads.
The lock gets released when the transaction is either commited/rolled back.