sql server死锁

This article explains the deadlock definition in SQL Server, and it also mentions how to capture deadlocks with extended events.

本文介绍了SQL Server中的死锁定义,还介绍了如何捕获具有扩展事件的死锁。

Deadlock is a resource contention issue that occurs between two or more than two processes. To handle this problem, we need to clearly understand how it occurs.

死锁是在两个或两个以上进程之间发生的资源争用问题。 为了解决这个问题,我们需要清楚地了解它是如何发生的。

死锁定义 (Deadlock Definition)

Deadlocks occur when two processes want to access resources that are mutually being locked by each other. This locked situation can continue forever if nobody stops it. Assume that two plumbers are making some repair in the same bathroom, and one of them is using a plunger and require wrench at the same time in his repair. The other one is using a wrench and required a plunger at the same time in his repair. Otherwise, none of them can complete their work.

当两个进程要访问相互锁定的资源时,就会发生死锁。 如果没有人阻止,这种锁定的情况可能永远持续下去。 假设有两个水管工正在同一间浴室进行维修,其中一个正在使用柱塞,并且在维修时需要同时使用扳手。 另一人正在使用扳手,并且在修理时同时需要柱塞。 否则,他们都无法完成工作。

After waiting for a while, the boss decided to abort one of the repairing processes so that one of the plumbers obtain the required resource and can complete his repair.

等待了一会儿后,老板决定中止其中一个维修过程,以便一名水管工获得所需的资源并可以完成维修。

This example mainly explained how deadlock occurs in a scenario.

此示例主要说明在方案中如何发生死锁。

SQL Server中的死锁定义 (Deadlock definition in SQL Server)

In terms of SQL Server, a deadlock occurs when two (or more) processes lock the separate resource. Under these circumstances, each process cannot continue and begins to wait for others to release the resource. However, the SQL engine understands that this contention would never end with the help of the lock manager warning and then it decides to kill one process to solve this conflict problem so that the other process can be completed. The killed process is called the deadlock victim.

对于SQL Server,当两个(或更多)进程锁定单独的资源时,将发生死锁。 在这种情况下,每个进程将无法继续,并开始等待其他进程释放资源。 但是,SQL引擎知道在锁管理器警告的帮助下该争用将永远不会结束,然后它决定终止一个进程来解决此冲突问题,从而可以完成另一个进程。 被杀死的进程称为死锁受害者。

在SQL Server中模拟死锁 (Simulate a deadlock in SQL Server)

After all these theoretical details, we will simulate a deadlock in SQL Server so that we can reinforce our learnings practically. At first, we will create two tables and insert some random data.

在所有这些理论细节之后,我们将在SQL Server中模拟死锁,以便我们可以切实加强我们的学习。 首先,我们将创建两个表并插入一些随机数据。

DROP TABLE IF EXISTS Table_ACREATE TABLE Table_A (Id INT PRIMARY KEY, FruitName VARCHAR(100))GOINSERT INTO Table_A VALUES(1,'Lemon')INSERT INTO Table_A VALUES(2,'Apple')GODROP TABLE IF EXISTS Table_BCREATE TABLE Table_B (Id INT PRIMARY KEY, FruitName VARCHAR(100))GOINSERT INTO  Table_B VALUES(1,'Banana')INSERT INTO Table_B VALUES(2,'Orange')
GO

As we explained in the deadlock definition, we need at least two processes for the deadlock, so that we will execute the following queries at the same time in the separated query windows.

正如我们在死锁定义中解释的那样,我们至少需要两个进程来处理死锁,以便我们将在分离的查询窗口中同时执行以下查询。

SET TRANSACTION ISOLATION LEVEL READ COMMITTEDBEGIN TRANUPDATE Table_A SET FruitName ='Mango' WHERE Id=1WAITFOR DELAY '00:00:08'UPDATE Table_B SET FruitName ='Avacado' WHERE Id=1COMMIT TRANSET TRANSACTION ISOLATION LEVEL READ COMMITTEDBEGIN TRANUPDATE Table_B SET FruitName ='Papaya' WHERE Id=1WAITFOR DELAY '00:00:08'UPDATE Table_A SET FruitName ='Kiwi' WHERE Id=1
COMMIT TRAN

As we can see that, the session 76 acquired a lock on table A and wanted to acquire a lock on the table B. At the same time, session 78 acquired a lock on table B and wanted to acquire a lock on the table A. In this circumstance, both of the sessions conflict each other and cannot proceed. Finally, SQL Server has chosen a victim and rollbacked this session. For our case, session 78 selected as a deadlock victim. The following image illustrates this scenario.

如我们所见,会话76获得了对表A的锁定,并希望获得对表B的锁定。同时,会话78获得了对表B的锁定,并希望获得对表A的锁定。在这种情况下,两个会话都相互冲突,无法继续进行。 最后,SQL Server选择了一个受害者并回滚了该会话。 对于我们的案例,第78节被选为死锁受害者。 下图说明了这种情况。

SQL chooses the victim according to the cost of the rollback. It means that the victim of the process has been decided based on the minimum resource consumption.

SQL根据回滚的成本选择受害者。 这意味着该过程的受害者是根据最小的资源消耗确定的。

使用扩展事件捕获僵局 (Capturing the Deadlocks with Extended Events)

Extended events are used to collect and monitor various events and information from SQL Server. With the help of the extended events, we can easily capture details when a deadlock occurred.

扩展事件用于从SQL Server收集和监视各种事件和信息。 借助扩展事件,当发生死锁时,我们可以轻松捕获细节。

At first, we will launch SQL Server Management Studio (SSMS) and navigate to Session, which is located under the Management folder. Right-click on the Sessions and select the New Session Wizard.

首先,我们将启动SQL Server Management Studio(SSMS)并导航到Session ,它位于Management文件夹下。 右键单击会话,然后选择新建会话向导。

We will click the Next button and skip to the next screen on the Introduction screen.

我们将单击“ 下一步”按钮,然后跳到“ 简介”屏幕上的下一个屏幕。

In the Set Session Properties screen, we will give a name to the extended event and click the Next button.

在“ 设置会话属性”屏幕中,我们将为扩展事件命名,然后单击“ 下一步”按钮。

On the Choose Template screen, we will select the Do not use a template option and click the Next button.

在“ 选择模板”屏幕上,我们将选择“不使用模板”选项,然后单击“ 下一步”按钮。

On the Select Events To Capture screen, we will add the following events from the Event library to Selected events list.

在“ 选择要捕获的事件”屏幕上,我们将以下事件从事件库添加到“ 选定事件”列表中。

  • database_xml_deadlock_report database_xml_deadlock_report
  • lock_deadlock lock_deadlock
  • lock_deadlock_chain lock_deadlock_chain
  • scheduler_monitor_deadlocks_ring_buffer_recorded scheduler_monitor_deadlocks_ring_buffer_recorded
  • xml_deadlock_report xml_deadlock_report
  • xml_deadlock_report_filtered xml_deadlock_report_filtered

On the Capture Global Fields screen, we will select global events that will be captured with the events:

在“ 捕获全局字段”屏幕上,我们将选择将与事件一起捕获的全局事件:

  • client app name 客户端应用名称
  • client connection id 客户端连接ID
  • client hostname 客户端主机名
  • database id 数据库ID
  • database name 数据库名称
  • nt username nt用户名
  • sql text sql文本
  • username 用户名

On the Specify Session Data Storage screen, we will set the target_file path that the events will be stored and we also set the maximum size of the event file.

在“ 指定会话数据存储”屏幕上,我们将设置将存储事件的target_file路径,并且还将设置事件文件的最大大小。

In this step, we will click the Finish button and create an extended event.

在此步骤中,我们将单击“ 完成”按钮并创建一个扩展事件。

On the final step, we will check the Start the event session immediately option and click the Close button. This will cause the extended event to capture deadlocks occurring on the SQL Server.

在最后一步,我们将选中“ 立即启动事件会话”选项,然后单击“ 关闭”按钮。 这将导致扩展事件捕获SQL Server上发生的死锁。

Now, we will re-execute deadlock simulating queries at the same time on the separated query windows and generate a deadlock error again.

现在,我们将在分离的查询窗口上同时重新执行死锁模拟查询,并再次生成死锁错误。

We will right-click on the created extended event and select the View Target Data… to analyze the captured deadlock details.

我们将右键单击创建的扩展事件,然后选择“ 查看目标数据”以分析捕获的死锁详细信息。

On this screen, we can display the deadlock details.

在此屏幕上,我们可以显示死锁详细信息。

When we click the xml_report field on the xml_deadlock_report event, the XML report of the deadlock will be opened. This report can be very helpful in understanding the details of the deadlock.

当我们单击xml_deadlock_report事件上的xml_report字段时,将打开死锁的XML报告。 该报告对于了解死锁的细节可能非常有帮助。

Also, in the xml_deadlock_report event, we can see the deadlock graph and it offers a virtual representation of the deadlock.

另外,在xml_deadlock_report事件中,我们可以看到死锁图 ,它提供了死锁的虚拟表示。

防止SQL Server中的死锁 (Preventing Deadlocks in SQL Server)

There is no exact and clear resolving formula for the deadlocks because all deadlocks might have unique characteristics. However, it is significant to understand the circumstances and the situation under which these deadlocks have occurred because this approach will broadly help to resolve them. After then, the following solution recommendations might help.

对于死锁,没有确切而明确的解决方案,因为所有死锁都可能具有独特的特征。 但是,重要的是要了解发生这些僵局的情况和情况,因为这种方法将在很大程度上帮助解决这些僵局。 之后,以下解决方案建议可能会有所帮助。

  • Access the resources in the same order 以相同的顺序访问资源
  • Write the shortest transactions as much as possible and lock the resource for the minimum duration 尽可能编写最短的事务,并在最短的时间内锁定资源
  • READ COMMITTED SNAPSHOT ISOLATION and READ COMMITTED SNAPSHOT ISOLATIONSNAPSHOT ISOLATION levels SNAPSHOT ISOLATION级别
  • Limiting the usage of the cursors 限制游标的使用
  • Design more normalized databases 设计更多标准化的数据库
  • Avoid poorly-optimized queries 避免优化不佳的查询

结论 (Conclusion)

Resolving the deadlock can be more complicated and struggling, so as a first step, we should clearly understand the deadlock definition and then set to work capturing and handling the deadlocks. In the final step, we can work on preventing or minimizing the deadlock.

解决死锁可能更加复杂且困难,因此,第一步,我们应该清楚地了解死锁的定义,然后开始捕获和处理死锁。 在最后一步,我们可以努力防止或最小化死锁。

翻译自: https://www.sqlshack.com/understanding-the-deadlock-definition-in-sql-server/

sql server死锁

sql server死锁_了解SQL Server中的死锁定义相关推荐

  1. java 解决死锁_如何解决java中的死锁问题

    一.死锁的定义 死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去. 那么我们换一个更加规范的定义:集合中的每一个进程都在 ...

  2. sql server死锁_了解SQL Server中的死锁图的XML描述

    sql server死锁 介绍 (Introduction) 在我的前两篇文章" What is a SQL Server Deadlock and 什么是SQL Server死锁" ...

  3. sql活动监视器 死锁_监视SQL Server死锁–简单方法

    sql活动监视器 死锁 SQL Server is a very powerful tool and wherever I go, I see the tool being way much unde ...

  4. sql server死锁_了解SQL Server死锁图的图形表示

    sql server死锁 #contentor img { float: left; } #contentor img { float: left; } 介绍 (Introduction) If yo ...

  5. sql server序列_在SQL Server中实现序列聚类

    sql server序列 In this article, we will be discussing Microsoft Sequence Clustering in SQL Server. Thi ...

  6. sql server 架构_在SQL Server中引入架构文档

    sql server 架构 描述 (Description) We often have a need to view object definitions in SQL Server, whethe ...

  7. sql server作业_在SQL Server中报告作业失败并发出警报

    sql server作业 SQL Server Agent can be used to run a wide variety of tasks within SQL Server. The buil ...

  8. sql docker容器_了解SQL Server Docker容器中的备份和还原操作

    sql docker容器 In this 17th article of the series (see the full article index at bottom), we will disc ...

  9. sql server 缓存_了解SQL Server查询计划缓存

    sql server 缓存 Whenever a query is run for the first time in SQL Server, it is compiled and a query p ...

最新文章

  1. 天天动听 悬浮歌词(迷你歌词)效果解读
  2. P3879 [TJOI2010]阅读理解 [STL]
  3. trackr: An AngularJS app with a Java 8 backend – Part IV 实践篇
  4. (Java集合框架)集合框架概述和Collection常用功能及遍历
  5. 第四范式获批工信部工业和信息化人才培养工程培训基地
  6. Scala重写父类普通方法
  7. centos7 和centos 6的一些区别
  8. POJ3263-Tallest Cow【前缀和】
  9. 负载(Load)分析及问题排查
  10. C++:获取图片文件信息-图片名称、类型、像素宽高
  11. 【linux】Permission denied (publickey) SSH用户名密码登录报错
  12. 概率论 —— 分析计算机系统和网络的可靠性和通用性
  13. Inno Setup入门(三)——指定压缩方式
  14. C#打印机套打三联单
  15. 这五款小众软件你肯定不知道
  16. chrome插件之vimium,解放你的鼠标
  17. 京沪高铁上火车位置的实时监视模拟网站的开发
  18. pacemaker和keepalived的区别
  19. 麻将公式一定要背下来「大全」
  20. 计算机网络基础知识满昌勇,中职中专学校《计算机网络基础》教学大纲可打印.doc...

热门文章

  1. CentOS环境设置Hbase自启动
  2. 常见的四种文本自动分词详解及IK Analyze的代码实现
  3. Strut2页面传参跳转 --Struts2
  4. mysql的建表语句
  5. callback 模式
  6. 菜鸟学习Spring——初识Spring
  7. 在DataGridView中的列头添加复选框
  8. 通过 JavaScript 获取/设置元素样式的方法
  9. HTML、CSS、JS对unicode编码字符的规则
  10. HIT Software Construction Review Notes(1-2 Quality Objectives of Software Construction)