views:

45

answers:

1

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

+1  A: 

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.

SET XACT_ABORT ON;
BEGIN TRAN
    SELECT * FROM <<TABLENAME>> WITH(UPDLOCK, SERIALIZABLE) WHERE 1=0;
    -- DO STUFF
    SELECT * FROM sys.dm_tran_locks WHERE request_session_id = @@spid;
COMMIT TRAN

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.

SET XACT_ABORT ON;
BEGIN TRAN
    DELETE FROM <<TABLENAME>> WITH(XLOCK, TABLOCK, SERIALIZABLE) WHERE 1=0;
    -- DO STUFF 
    SELECT * FROM sys.dm_tran_locks WHERE request_session_id = @@spid;
COMMIT TRAN

The lock gets released when the transaction is either commited/rolled back.

etliens
for the X lock, why are you doing a delete? can't you do a select?
pdiddy
yes, however, I wanted to avoid actually returning any rows.
etliens