— by Lori Brown @SQLSupahStah
Periodically, all DBA’s are going to run into code that fails due to a deadlock. Deadlocks happen when two or more SPIDs\sessions try to access a resource that is locked by each other. In short, something has to give so one is usually chosen by SQL to be the victim meaning one is the loser. Deadlocks can be avoided by designing your databases well and making queries as quick and lightweight as possible. The faster data is retrieved or locked and unlocked the better.
But, how do you figure out what is causing deadlocks if you suddenly run into them? An easy way is to use the information that is already captured in the default system_health session information that is already being gathered by SQL.
Here are queries to retrieve this information from SQL 2008 R2 and SQL 2012 and up.
— get deadlock graphs in SQL 2008
SELECT CAST(event_data.value(‘(event/data/value)[1]’,
‘varchar(max)’) AS XML) AS DeadlockGraph
FROM ( SELECT XEvent.query(‘.’) AS event_data
FROM ( — Cast the target_data to XML
SELECT CAST(target_data AS XML) AS TargetData
FROM sys.dm_xe_session_targets st
JOIN sys.dm_xe_sessions s
ON s.address = st.event_session_address
WHERE name = ‘system_health’
AND target_name = ‘ring_buffer’
) AS Data — Split out the Event Nodes
CROSS APPLY TargetData.nodes(‘RingBufferTarget/
event[@name=”xml_deadlock_report”]’)
AS XEventData ( XEvent )
) AS tab ( event_data );
— get deadlock graphs in SQL 2012 and up
SELECT XEvent.query(‘(event/data/value/deadlock)[1]’) AS DeadlockGraph
FROM ( SELECT XEvent.query(‘.’) AS XEvent
FROM ( SELECT CAST(target_data AS XML) AS TargetData
FROM sys.dm_xe_session_targets st
JOIN sys.dm_xe_sessions s
ON s.address = st.event_session_address
WHERE s.name = ‘system_health’
AND st.target_name = ‘ring_buffer’
) AS Data
CROSS APPLY TargetData.nodes
(‘RingBufferTarget/event[@name=”xml_deadlock_report”]’)
AS XEventData ( XEvent )
) AS src;
Queries originally from Jonathan Kehayias (One super smart SQL guy!) https://www.simple-talk.com/author/jonathan-kehayias/
For more information about blog posts, concepts and definitions, further explanations, or questions you may have…please contact us at SQLRx@sqlrx.com. We will be happy to help! Leave a comment and feel free to track back to us. Visit us at www.sqlrx.com!