gpt4 book ai didi

sql-server - sql server死锁案例

转载 作者:行者123 更新时间:2023-12-04 01:08:48 24 4
gpt4 key购买 nike

我在同一个表中插入数据的 2 个进程之间存在死锁问题这 2 个进程在具有主键(标识)和唯一索引的表上运行完全相同的 SQL 命令。

对于显式事务中的每个进程,SQL 顺序的顺序如下:

begin trans

select CUSTID from CUSTOMERS where CUSTNUMBER='unique value'

------- the row is never found in this case so... insert the data
insert into CUST(CUSTNUMBER) values('unique value')

------- then we must read the value generated for the pk
select CUSTID from CUSTOMERS where CUSTNUMBER='unique value'

commit

每个进程都处理不同的数据集,并且“CUSTNUMBER”没有共同的值

死锁发生在这种情况下:

spid 1 : 选择 custid... 作为唯一值 1

spid 2 : 选择 custid... 作为唯一值 2

spid 1 : 插入唯一值 1

spid 2 : 插入唯一值 2

spid 2 : 再次为值 2 选择 custid <--- Deadlock Victim !

spid 1 : 再次为值 1 选择 custid

死锁图显示问题出现在 CUSTNUMBER 的唯一索引上

被杀死的进程有一个锁 OwnerMode:X 并且在同一 HoBt ID 的唯一索引上是 RequestMode:S。对于相同的 HoBt ID,获胜进程是 OnwerMode:X 和 RequestMode:S

我不知道如何解释,也许有人可以帮助我?

最佳答案

尝试使用 OUTPUT 去掉最后的 SELECT:

begin trans

select CUSTID from CUSTOMERS where CUSTNUMBER='unique value'

------- the row is never found in this case so... insert the data
insert into CUST(CUSTNUMBER) OUTPUT INSERTED.CUSTID values('unique value')
--^^^^^^^^^^^^^^^ will return a result set of CUSTIDs

commit

DECLARE @x table (CUSTID  int)
begin trans

select CUSTID from CUSTOMERS where CUSTNUMBER='unique value'

------- the row is never found in this case so... insert the data
insert into CUST(CUSTNUMBER) OUTPUT INSERTED.CUSTID INTO @x values('unique valu')
--^^^^^^^^^^^^^^^^^^^^^^ will store a set of CUSTIDs
-- into the @x table variable

commit

关于sql-server - sql server死锁案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com