简体   繁体   English

死锁在 Sql Server 中执行查询

[英]Deadlock executing Query in Sql Server

I've the following Linq:我有以下 Linq:

var qry = s.GetTable<MessageEventDTO>().Where(x => x.MessageName == messageName && x.SourceTyp == sourceTyp && x.Source == source && (x.Status == MessageEventStatus.open || x.Status == MessageEventStatus.acknowledged));

goneMessages = qry.ToList();

var ret = qry
    .Set(x => x.Status, x => x.Status | MessageEventStatus.gone)
    .Set(x => x.TimestampGone, timeStamp)
    .Update();
return ret;

which will be converted to following SQL:它将转换为以下 SQL:

UPDATE MessageEvents SET Status = Status | 1, TimeStampGone = @1
WHERE MessageName = @2 AND SourceTyp = @3 Source = @4 AND (Status = 0 OR Status = 2)

the problem is now, there are multiple Updates run in parallel, and I got deadlock exceptions, but I do not understand why?现在的问题是,有多个更新并行运行,我得到了死锁异常,但我不明白为什么?

see also也可以看看
在此处输入图片说明

在此处输入图片说明

If you don't want another process to be able to start the select portion of the update, use the UPDLOCK hint or set an appropriate transaction isolation level ( REPEATABLE READ ).如果您不希望其他进程能够启动更新的选择部分,请使用UPDLOCK提示或设置适当的事务隔离级别 ( REPEATABLE READ )。

See John Huang's Blog for a more thorough explanation of how nonclustered indexes can cause deadlocks.有关非聚集索引如何导致死锁的更详细说明,请参阅John Huang 的博客

Example using Linq to SQL which is not prey to this issue:使用 Linq to SQL 的示例不受此问题的影响:

var opts = new TransactionOptions();
opts.IsolationLevel = IsolationLevel.RepeatableRead;
using (var txn = new TransactionScope(TransactionScopeOption.Required, opts))
{
    // update command goes here.

    txn.Complete();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM