如何查看事务sql中设置了哪个锁?

时间:2017-12-09 09:51:10

标签: sql sql-server multithreading locking

我想演示此示例

中丢失的更新问题
Create table tblInventory
(
    Id int,
    Name varchar(50),
    ItemsInStock int
    Constraint PK_PRODUCT
    Primary key (Id)
)
Insert tblInventory
Values (1,'Iphone',10) 
 -- Transaction 1
 Begin Tran
 Declare @ItemsInStock int

 Select @ItemsInStock = ItemsInStock
 from tblInventory where Id=1

 -- Transaction takes 10 seconds

 Waitfor Delay '00:00:10'
 Set @ItemsInStock = @ItemsInStock - 1

 Update tblInventory
 Set ItemsInStock = @ItemsInStock where Id=1

 Print @ItemsInStock

 Commit Transaction


 -- Transaction 2
 Begin Tran
 Declare @ItemsInStock int

 Select @ItemsInStock = ItemsInStock
 from tblInventory where Id=1

 -- Transaction takes 1 second
 Waitfor Delay '00:00:1'
 Set @ItemsInStock = @ItemsInStock - 2

 Update tblInventory
 Set ItemsInStock = @ItemsInStock where Id=1

 Print @ItemsInStock

 Commit Transaction

这个例子来自这个链接:http://csharp-video-tutorials.blogspot.com/2015/08/sql-server-lost-update-problem.html

此示例将损坏丢失的更新,我想要求无论如何都要在SQL Server上显示在事务1和2中设置的锁,如下所示:

选择=>锁定类型:S(共享锁定)=>隔离级别:Read Committed

更新=>锁定类型:X(独占锁定)=>隔离级别:Read Committed

据我所知,当选择我们将获得共享锁时,更新时我们将获得独占锁,但我想在SQL Server中显示它

我尝试使用sp_who和sp_lock但不显示我想要的结果

我正在使用SQL Server 2008 R2

PS:/我有一个小问题,如何通过查询来了解哪个事务可以丢失更新问题?

感谢任何帮助。

提前致谢。

1 个答案:

答案 0 :(得分:0)

创建包含lock_acquired和lock_released事件的扩展事件跟踪。添加过滤器以仅跟踪感兴趣的会话。

下面是一个会话的跟踪示例DDL,该会话将事件写入跟踪文件,在session_id上过滤了2个会话。可以从SSMS启动,停止和查看跟踪(管理 - >扩展事件 - >会话。

CREATE EVENT SESSION [locks] ON SERVER 
ADD EVENT sqlserver.lock_acquired(SET collect_resource_description=(1)
    ACTION(sqlserver.session_id,sqlserver.sql_text)
    WHERE ([sqlserver].[session_id]=(56) OR [sqlserver].[session_id]=(57))),
ADD EVENT sqlserver.lock_released(SET collect_resource_description=(1)
    ACTION(sqlserver.session_id,sqlserver.sql_text)
    WHERE ([sqlserver].[session_id]=(56) OR [sqlserver].[session_id]=(57)))
ADD TARGET package0.event_file(SET filename=N'locks')
WITH (MAX_MEMORY=1048576 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)
GO