如何排查SQL死锁的错误?
什么是死锁?
==============
A deadlock occurs when two system server process IDs (SPIDs) are waiting for a resource and neither process can advance because the other process is preventing it from getting the resource. For example, Andrew holds a lock on table A and requests a lock on table B; Lindsay holds a lock on table B and requests a lock on table A.
什么东西可以引发死锁?
==============
- Locks
- Worker threads
- Memory
- Parallel query execution-related resources
- Multiple Active Result Sets (MARS) resources.
如何排查死锁?
==============
1. 开启死锁日志输出(deadlock trace)
DBCC TRACEON(1204,1222)
Trace flag 1204 reports deadlock information formatted by each node involved in the deadlock.
Trace flag 1222 formats deadlock information, first by processes and then by resources.
开启了上面的选项之后, SQL会输出死锁的细节信息到SQL Error Log中(默认位置Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n)
2. 开启SQL Profiler.
- Start SQL profiler
- On the Trace Properties dialog box, on the General tab, check Save to file and specify a path to save the trace
- Click the Events tab, only add Locks\Lock:deadlock and Locks\Lock:deadlock chain
- Click the Data columns tab, add DatabaseID, IndexID, ObjectID
可以通过下面的语句把DatabaseID和ObjectID换成DatabaseName和ObjectName
SELECT database_name(DatabaseID) SELECT object_name(ObjectID)
3. 使用下面的查询语句来检查那个进程被锁住了.
SELECT * FROM sys.sysprocesses WHERE blocked <> 0 从Blocked列中得到SPID DBCC inputbuffer (SPID) sp_who2 sp_lock2
参考资料:
SQL: How to debug SQL deadlocks
http://www.dalun.com/blogs/10.13.2006.htm
SQL Server technical bulletin - How to resolve a deadlock
http://support.microsoft.com/?kbid=832524
Detecting and Ending Deadlocks
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律