你可以在交易期間使用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
親愛的波格丹,謝謝你的建議。我從我的經理那裏得到的另一個解決方案是利用同一個表中的'LoggedInUser'字段,並執行當前'LoggedInUser'特有的DML以避免併發問題。 –
@sujimon:也許如果你給我關於你的問題的更多細節,我可以幫助你更多。在這一刻,我沒有看到任何有關你的問題中的「LoggedInUser」列的信息。 –
我想我沒有正確地解決我的問題。沒有任何數據庫鎖定在桌面上我最好。我只是想解決多用戶環境中的併發問題。我後來發現可以通過A>識別登錄的用戶配置文件B>識別訪問應用程序的計算機名稱C>在存儲過程中使用表變量。但我同意你關於表鎖,所以我將這標記爲答案! –