Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- -- Initialization:
- CREATE DATABASE TestRCSI
- ALTER DATABASE TestRCSI SET ALLOW_SNAPSHOT_ISOLATION ON
- GO
- USE TestRCSI
- CREATE TABLE T (X CHAR(3) PRIMARY KEY)
- */
- GO
- -- try running this script in two SSMS windows (after executing the initialization above in only one of those windows)
- USE TestRCSI
- GO
- SET TRANSACTION ISOLATION LEVEL SNAPSHOT
- SET XACT_ABORT ON
- SET NOCOUNT ON
- DECLARE @x CHAR(3)
- start:
- SET @x=LEFT(CONVERT(CHAR(36),NEWID()),3)
- BEGIN TRAN
- INSERT INTO T SELECT @x
- WHERE NOT EXISTS (SELECT * FROM T WITH (UPDLOCK) WHERE X=@x)
- -- in the above statement we also need a HOLDLOCK hint, else we will eventually get a violation of the PK
- COMMIT
- --IF @@ROWCOUNT=0 DELETE T WHERE x>'A'
- IF @@ROWCOUNT=0 BEGIN
- BEGIN TRAN
- IF EXISTS (SELECT * FROM T WITH (TABLOCKX,HOLDLOCK) WHERE X>'A') BEGIN
- -- we need to check if there are matching rows before deleting, else we will get a deadlock
- DELETE T WHERE X>'A'
- END
- COMMIT
- END
- GOTO start
- GO
- /*
- -- Cleanup:
- USE master
- DROP DATABASE TestRCSI
- */
Add Comment
Please, Sign In to add comment