我想在并发访问的情况下锁定某个表。
在存储过程中:
为了避免在发生并发访问时出现问题,我计划添加一个'BEGIN TRANSACTION',然后是'BEGIN TRY -END TRY'和'BEGIN CATCH - END CATCH'。我'COMMIT'就在'END-TRY'之前,'ROLLBACK'在'CATCH'里面。
这将解决所有并发问题,还是我需要做更多的事情。
非常感谢, Sujit
答案 0 :(得分:2)
您可以在使用TABLOCK
或TABLOCKX
(references)的交易中锁定整个表格:
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事件探查器输出):
注意:SELECT OBJECT_ID(N'dbo.MyTable')
= 1316199739