一、LCK_M_S,等待获取共享锁
开始一SQL TRAN,其中执行对某数据的UPDATE。但并不COMMIT,也不ROLLBACK。
begin tranupdate [dbo].[HR_Employee] set [Description]='ZZ'
这样,便使用排它锁锁定了该[Employee]表。
在另一会话中,执行对该表的SELECT操作。至此,死锁产生。
select * from [dbo].[HR_Employee]
使用下列script查询当前锁情况。
1 SELECT wt.blocking_session_id AS BlockingSessesionId 2 ,sp.PRogram_name AS ProgramName 3 ,COALESCE(sp.LOGINAME, sp.nt_username) AS HostName 4 ,ec1.client_net_address AS ClientIpAddress 5 ,db.name AS DatabaseName 6 ,wt.wait_type AS WaitType 7 ,ec1.connect_time AS BlockingStartTime 8 ,wt.WAIT_DURATION_MS/1000 AS WaitDuration 9 ,ec1.session_id AS BlockedSessionId10 ,h1.TEXT AS BlockedSQLText11 ,h2.TEXT AS BlockingSQLText12 FROM sys.dm_tran_locks AS tl13 INNER JOIN sys.databases db14 ON db.database_id = tl.resource_database_id15 INNER JOIN sys.dm_os_waiting_tasks AS wt16 ON tl.lock_owner_address = wt.resource_address17 INNER JOIN sys.dm_exec_connections ec118 ON ec1.session_id = tl.request_session_id19 INNER JOIN sys.dm_exec_connections ec220 ON ec2.session_id = wt.blocking_session_id21 LEFT OUTER JOIN master.dbo.sysprocesses sp22 ON SP.spid = wt.blocking_session_id23 CROSS APPLY sys.dm_exec_sql_text(ec1.most_recent_sql_handle) AS h124 CROSS APPLY sys.dm_exec_sql_text(ec2.most_recent_sql_handle) AS h2
发现该LOCK的wait_type为LCK_M_S,意味着后一会话在等待着获取对该表的共享锁已完成查询工作。
二、LCK_M_U,等待获取更新锁。
发起一SQL会话,在其中使用更新锁(UPDLOCK)SELECT数据,而后WAIT一定的时间。
1 begin tran2 select * from [dbo].[HR_Employee] WITH (UPDLOCK) where [Id]=73 waitfor delay '00:01:00' 4 update [dbo].[HR_Employee] set [Description]='ZZ' where [Id]=75 commit tran
在wait的时间内,[Id]=7的行被更新锁锁住。
发起另一会话,使用更新锁(UPDLOCK)完成SELECT操作。
1 select * from [dbo].[HR_Employee] WITH (UPDLOCK)
发现后一会话被block。wait_type为LCK_M_U,表示其在等待该表的更新锁。
三、LCK_M_X,等待获取排它锁
将上一小节中第二个会话的操作改为UPDATE。
update [dbo].[HR_Employee] set [Description]='ZZy' where [Id]=7
后一会话同样被block,但这次的wait_type为LCK_M_X,表明其在等待用于UPDATE DATA的排它锁。
新闻热点
疑难解答