T-SQL query to find deadlocks in SQL Server

Earlier, I wrote an article about using extended events to to find the deadlocks occurring on a SQL Server. Extended events will be a great help to track the deadlocks happened on the server for short period of time, especially on a production environment. However, In the development environment, I came across situations where the ongoing long duration deadlocks appearing when multiple developers trying to execute dml statements against a table. During such situations, I used a light weight T-SQL query to find deadlocks i.e, blocking and blocked session-ids of SQL connections. Based on the details returned by this statement, I was able to find the application or user which has executed the blocking session and helped me to kill the specific SQL connection. It also helped us to identify and fix the frequently blocking SQL statement.

Below is the query I have used to quickly find the deadlocks. This statement is based on the SYS.DM_EXEC_REQUESTS dynamic management view. In this statement, the column blocking_session_id gives you the session_id of the connection which is blocking and the column wait_type gives you the type of wait which caused the deadlock. After getting the blocking_session_id, you can use another dmv SYS.DM_EXEC_SESSIONS to get more details about the session or connection.

	Definition = CAST(text AS VARCHAR(MAX))
	CROSS APPLY sys.dm_exec_sql_text(sql_handle) 
WHERE blocking_session_id != 0
T-SQL query to find deadlocks in SQL Server

Hope this simple query to find deadlocks will be helpful to you all.


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.