How to Find Blocking and Deadlock in SQL Server

本文最后更新于:2024年8月9日 晚上


  • What is deadlock in SQL Server?
  • What is Blocking in SQL Server?
  • What is difference between deadlock and blocking in SQL Server?
  • How to create deliberate deadlock for learning purposes?
  • What are the deadlock traces in SQL Server?
  • How to turn on deadlock traces on and off in SQL Server?
  • How and where to check deadlock information in SQL Server?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--How to check blocking in SQL Server
Exec sp_who;
GO

--How to turn on and off traces and check Traces on SQL Server
DBCC TRACESTATUS();

--How to check If Deadlock traces are enabled or disabled
DBCC TRACESTATUS(1204,1222, -1)

--How to Turn Deadlock Traces on SQL Server
DBCC TRACEON(1204,1222, -1)

--How to Turn deadlock Traces Off
DBCC TRACEOFF(1204,1222, -1)
1
2
3
4
5
6
7
--create deliberate deadlock
-- Tran1
CREATE TABLE DemoDeadLock1 (SessionNumber INT)
INSERT DemoDeadLock1 SELECT 1

CREATE TABLE DemoDeadLock2 (SessionNumber INT)
INSERT DemoDeadLock2 SELECT 1
1
2
3
--Tran2 in new session
BEGIN TRAN
UPDATE DemoDeadLock1 SET SessionNumber= 1
1
2
3
4
--Tran3
BEGIN TRAN
UPDATE DemoDeadLock2 SET SessionNumber = 1
UPDATE DemoDeadLock1 SET SessionNumber = 1
1
2
--update Demodeadlock2 table in our Tran2 session
UPDATE DemoDeadLock2 SET SessionNumber = 1

How to Find Blocking and Deadlock in SQL Server
https://git.msft.vip/2022/09/19-sql-server-deadlock-and-blocking/
作者
Jas0n0ss
发布于
2022年9月20日
更新于
2024年8月9日
许可协议