Tag Archives: deadlock

Check and resolve blocking in Microsoft SQL Server

Check the blocking cause and resolve the issue in Microsoft SQL Server

In the following example, Firstly we will create the blocking between two sessions and try to solve it by KILLcommand. I am using AdventureWorks database of SQL Server.

SESSION ONE: Begin one transaction but not end.

BEGIN TRAN
UPDATE [Person].[Address] SET City = 'DELHI' WHERE   AddressID = 70 

SESSION TWO: Execute the SELECT statement on the same table


select * from [Person].[Address];

SESSION THREE: execute sp_who2 command to get blocking information:

Get the cause of deadlock or blocking in SQL Server which query is blocking:

SELECT
db.name DBName,
tl.request_session_id,
wt.blocking_session_id,
OBJECT_NAME(p.OBJECT_ID) BlockedObjectName,
tl.resource_type,
h1.TEXT AS BlockedQuery,
h2.TEXT AS CauseofBlocking,
tl.request_mode
FROM sys.dm_tran_locks AS tl
INNER JOIN sys.databases db ON db.database_id = tl.resource_database_id
INNER JOIN sys.dm_os_waiting_tasks AS wt ON tl.lock_owner_address = wt.resource_address
INNER JOIN sys.partitions AS p ON p.hobt_id = tl.resource_associated_entity_id
INNER JOIN sys.dm_exec_connections ec1 ON ec1.session_id = tl.request_session_id
INNER JOIN sys.dm_exec_connections ec2 ON ec2.session_id = wt.blocking_session_id
CROSS APPLY sys.dm_exec_sql_text(ec1.most_recent_sql_handle) AS h1
CROSS APPLY sys.dm_exec_sql_text(ec2.most_recent_sql_handle) AS h2

Output:

Query 2: To identify the cause and queries of blocking:


WITH cteBL (session_id, blocking_these) AS 
(SELECT s.session_id, blocking_these = x.blocking_these FROM sys.dm_exec_sessions s 
CROSS APPLY    (SELECT isnull(convert(varchar(6), er.session_id),'') + ', '  
                FROM sys.dm_exec_requests as er
                WHERE er.blocking_session_id = isnull(s.session_id ,0)
                AND er.blocking_session_id <> 0
                FOR XML PATH('') ) AS x (blocking_these)
)
SELECT s.session_id, blocked_by = r.blocking_session_id, bl.blocking_these
, batch_text = t.text, input_buffer = ib.event_info, * 
FROM sys.dm_exec_sessions s 
LEFT OUTER JOIN sys.dm_exec_requests r on r.session_id = s.session_id
INNER JOIN cteBL as bl on s.session_id = bl.session_id
OUTER APPLY sys.dm_exec_sql_text (r.sql_handle) t
OUTER APPLY sys.dm_exec_input_buffer(s.session_id, NULL) AS ib
WHERE blocking_these is not null or r.blocking_session_id > 0
ORDER BY len(bl.blocking_these) desc, r.blocking_session_id desc, r.session_id;

Output:

Query from link: https://docs.microsoft.com/enus/troubleshoot/sql/performance/understand-resolve-blocking

For resolving the issue, we have to spot the session 60 which is causing problems:

KILL SESSION
Example:
KILL 60