rsocol

HOLDLOCK is also needed for snapshot isolation

Aug 21st, 2021 (edited)
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.05 KB | None | 0 0
  1. /*
  2. -- Initialization:
  3. CREATE DATABASE TestRCSI
  4. ALTER DATABASE TestRCSI SET ALLOW_SNAPSHOT_ISOLATION ON
  5. GO
  6. USE TestRCSI
  7. CREATE TABLE T (X CHAR(3) PRIMARY KEY)
  8. */
  9. GO
  10. -- try running this script in two SSMS windows (after executing the initialization above in only one of those windows)
  11. USE TestRCSI
  12. GO
  13. SET TRANSACTION ISOLATION LEVEL SNAPSHOT
  14. SET XACT_ABORT ON
  15. SET NOCOUNT ON
  16. DECLARE @x CHAR(3)
  17.  
  18. start:
  19. SET @x=LEFT(CONVERT(CHAR(36),NEWID()),3)
  20.  
  21. BEGIN TRAN
  22. INSERT INTO T SELECT @x
  23. WHERE NOT EXISTS (SELECT * FROM T WITH (UPDLOCK) WHERE X=@x)
  24. -- in the above statement we also need a HOLDLOCK hint, else we will eventually get a violation of the PK
  25. COMMIT
  26.  
  27. --IF @@ROWCOUNT=0 DELETE T WHERE x>'A'
  28. IF @@ROWCOUNT=0 BEGIN
  29.     BEGIN TRAN
  30.     IF EXISTS (SELECT * FROM T WITH (TABLOCKX,HOLDLOCK) WHERE X>'A') BEGIN
  31.         -- we need to check if there are matching rows before deleting, else we will get a deadlock
  32.         DELETE T WHERE X>'A'
  33.     END
  34.     COMMIT
  35. END
  36.  
  37. GOTO start
  38.  
  39. GO
  40. /*
  41. -- Cleanup:
  42. USE master
  43. DROP DATABASE TestRCSI
  44. */
  45.  
  46.  
Add Comment
Please, Sign In to add comment