XEvent--Demo--使用XEvent来捕获在数据库DB1上发生的锁请求和锁释放
--==============================================================
--使用XEvent来捕获在数据库DB1上发生的锁请求和锁释放
--==============================================================
--查看锁相关的事件
SELECT xp.[name] AS [Package_Name], xo.*
FROM sys.dm_xe_objects xo
INNER JOIN sys.dm_xe_packages xp
ON xp.[guid] = xo.[package_guid]
WHERE xo.name LIKE '%LOCK%'
--找到要研究的锁行为
--lock_acquired
--lock_released
--=============================================================
--创建回话[XE_LockMonitor]
--回话捕获在数据库DB1上发生的锁请求和锁释放
IF EXISTS(
SELECT *FROM sys.server_event_sessions
WHERE name='XE_LockMonitor'
)
BEGIN
DROP EVENT SESSION [XE_LockMonitor] ON SERVER;
END
GO
CREATE EVENT SESSION [XE_LockMonitor] ON SERVER
ADD EVENT sqlserver.lock_acquired(
ACTION(sqlserver.database_id,sqlserver.database_name,sqlserver.sql_text)
WHERE ([sqlserver].[database_name]=N'DB1')),
ADD EVENT sqlserver.lock_released(
ACTION(sqlserver.database_id,sqlserver.database_name,sqlserver.sql_text)
WHERE ([sqlserver].[database_name]=N'DB1'))
ADD TARGET package0.event_file(SET filename=N'E:\DB\XE_LockMonitor.xel')
WITH (STARTUP_STATE=OFF)
GO
--=============================================================
--启动回话
ALTER EVENT SESSION [XE_LockMonitor] ON SERVER
STATE=START;
GO
--=============================================================
USE DB1
GO
SELECT * FROM dbo.TB1
GO
--=============================================================
--停止回话
ALTER EVENT SESSION [XE_LockMonitor] ON SERVER
STATE=STOP;
GO
--=============================================================
--由于XEevent使用XML来存储结果,因此可以使用TSQL来查看结果,但是实现相对复杂
--使用SSMS在扩展回话事件里查看数据