Advertisement
rsocol

Proof that UPDLOCK is not enough (you also need HOLDLOCK)

Apr 29th, 2018
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 0.72 KB | None | 0 0
  1. -- try running this script in two SSMS windows
  2. USE tempdb
  3. IF OBJECT_ID('T') IS NULL CREATE TABLE T (X CHAR(3) PRIMARY KEY)
  4. GO
  5. SET XACT_ABORT ON
  6. SET NOCOUNT ON
  7. DECLARE @x CHAR(3)
  8.  
  9. start:
  10. SET @x=LEFT(CONVERT(CHAR(36),NEWID()),3)
  11.  
  12. INSERT INTO T SELECT @x
  13. WHERE NOT EXISTS (SELECT * FROM T WITH (UPDLOCK) WHERE X=@x)
  14. -- in the above statement we also need a HOLDLOCK hint, else we will eventually get a violation of the PK
  15.  
  16. --IF @@ROWCOUNT=0 DELETE T WHERE x>'A'
  17. IF @@ROWCOUNT=0 BEGIN
  18.     BEGIN TRAN
  19.     IF EXISTS (SELECT * FROM T WITH (TABLOCKX,HOLDLOCK) WHERE X>'A') BEGIN
  20.         -- we need to check if there are matching rows before deleting, else we will get a deadlock
  21.         DELETE T WHERE X>'A'
  22.     END
  23.     COMMIT
  24. END
  25.  
  26. GOTO start
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement