Skip to content

Instantly share code, notes, and snippets.

@guzmanda
Created June 24, 2019 21:21
Show Gist options
  • Save guzmanda/ef7d54eda7358da882293585a35a2f0f to your computer and use it in GitHub Desktop.
Save guzmanda/ef7d54eda7358da882293585a35a2f0f to your computer and use it in GitHub Desktop.
Get xml_deadlock_report from system_health session file target
--get xml_deadlock_report from system_health session file target
WITH
--get full path to current system_health trace file
CurrentSystemHealthTraceFile AS (
SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
FROM sys.dm_xe_session_targets
WHERE
target_name = 'event_file'
AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%\system[_]health%'
)
--get trace folder name and add base name of system_health trace file with wildcard
, BaseSystemHealthFileName AS (
SELECT
REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'\', REVERSE(FileName)), 255)) + N'system_health*.xel' AS FileNamePattern
FROM CurrentSystemHealthTraceFile
)
--get xml_deadlock_report events from all system_health trace files
, DeadLockReports AS (
SELECT CAST(event_data AS xml) AS event_data
FROM BaseSystemHealthFileName
CROSS APPLY sys.fn_xe_file_target_read_file ( FileNamePattern, NULL, NULL, NULL) AS xed
WHERE xed.object_name like 'xml_deadlock_report'
)
--display 10 most recent deadlocks
SELECT TOP 10
DATEADD(hour, DATEDIFF(hour, SYSUTCDATETIME(), SYSDATETIME()), event_data.value('(/event/@timestamp)[1]', 'datetime2')) AS LocalTime
, event_data AS DeadlockReport
FROM DeadLockReports
ORDER BY LocalTime ASC;
GO
@guzmanda
Copy link
Author

@nil96, the script in this gist should be run in it's entirety. With your current file name, the BaseSystemHealthFileName CTE will return 'D:\rdsdbdata\Log\system_health*.xel' and that wildcard path used in the DeadLockReports CTE to extract xml_deadlock_report events from all available system_health trace files. The final SELECT query will extract the 10 oldest events but you can change the order to DESC to get the most recent ones and change to TOP clause to return more or fewer as desired.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment