并发访问时的T-SQL锁资源

时间:2013-10-26 08:02:57

标签: sql-server tsql concurrency sqltransaction

我想在并发访问的情况下锁定某个表。

在存储过程中:

  • 我截断一个表
  • 进行计算并填充上表
  • 从PROCEDURE返回后,从表格中选择

为了避免在发生并发访问时出现问题,我计划添加一个'BEGIN TRANSACTION',然后是'BEGIN TRY -END TRY'和'BEGIN CATCH - END CATCH'。我'COMMIT'就在'END-TRY'之前,'ROLLBACK'在'CATCH'里面。

这将解决所有并发问题,还是我需要做更多的事情。

非常感谢, Sujit

1 个答案:

答案 0 :(得分:2)

您可以在使用TABLOCKTABLOCKXreferences)的交易中锁定整个表格:

BEGIN TRANSACTION;

-- For shared locking:    
-- This will take a S(shared) lock at table level for duration of transaction
-- SELECT TOP(0) * FROM dbo.MyTable WITH(TABLOCK,HOLDLOCK)
-- HOLDLOCK hint is needed in this case because 
-- default behavior at default transaction isolation level (READ COMMITTED) 
-- is to maintain a S lock only during record reading.

-- For exclusive locking:    
-- This will take a (x)X(clusive) lock at table level for duration of transaction
SELECT TOP(0) * FROM dbo.MyTable WITH(TABLOCKX)

ROLLBACK;

示例(SQL事件探查器输出):

enter image description here

注意:SELECT OBJECT_ID(N'dbo.MyTable') = 1316199739