SQL Server, the misleading XLOCK & optimizations

后端 未结 3 1449
面向向阳花
面向向阳花 2020-12-08 16:39

From some recent testing and reading I\'ve done, it seems the \"X\" (exclusive) name part of XLOCK is misleading. It in fact doesn\'t lock any more than UPDLOCK. If it were

3条回答
  •  执念已碎
    2020-12-08 16:45

    based on the comments in @Martin's answer, here is a little script (run the different parts in different SSMS windows to test the lock preventing a SELECT:

    --
    --how to lock/block a SELECT as well as UPDATE/DELETE on a particular row
    --
    
    --drop table MyTable
    --set up table to test with
    CREATE TABLE MyTable (RowID int primary key clustered
                         ,RowValue int unique nonclustered not null) 
    
    --populate test data
    ;WITH InsertData AS
    (
        SELECT 4321 AS Number
        UNION ALL
        SELECT Number+1
            FROM InsertData
            WHERE Number<9322
    )
    INSERT MyTable
            (RowID,RowValue)
        SELECT
            Number, 98765-Number
            FROM InsertData
            ORDER BY Number
        OPTION (MAXRECURSION 5001)
    
    -----------------------------------------------------------------------------
    -- #1
    --OPEN A NEW SSMS window and run this
    --
    --create lock to block select/insert/update/delete
    DECLARE @ID int
    
    BEGIN TRANSACTION
    
    SELECT @ID=RowID FROM MyTable WITH (ROWLOCK, XLOCK, HOLDLOCK) WHERE RowID=6822
    PRINT @ID
    
    --COMMIT  --<<

提交回复
热议问题