SQL Server表中的并行插入/更新

昆汀五世

我有一个多线程环境,每个线程都想要在表中选择一行(如果不存在,则将其插入)并在其中增加一些内容。

基本上,每个线程都执行以下操作:

using (var context = new Entity.DBContext()) {
    if(!context.MyTable.Any(...)) {
        var obj = new MyTable() {
            SomeValue = 0
        };
        context.MyTable.Add(obj)
    }
    var row = context.MyTable.SingleOrDefault(...);
    row.SomeValue += 1;
    context.SaveChanges();
}

示例中的问题:特定行的SomeValue =0。两个线程同时选择该特定行,它们都看到0。->它们都将其递增一次,而SomeValue的最终结果将为1,但是我们希望它是2。

我假设紧随另一个线程到达的线程应该等待(使用锁?)使第一个线程结束。但是我不能使其正常工作。

谢谢。

Damien_The_Unbeliever

假设使用SQL Server,您可以执行以下操作:

create table T1 (
    Key1 int not null,
    Key2 int not null,
    Cnt int not null
)
go
create procedure P1
    @Key1 int,
    @Key2 int
as
    merge into T1 WITH (HOLDLOCK) t
    using (select @Key1 k1,@Key2 k2) s
    on
        t.Key1 = s.k1 and
        t.Key2 = s.k2
    when matched then update set Cnt = Cnt + 1
    when not matched then insert (Key1,Key2,Cnt) values (s.k1,s.k2,0)
    output inserted.Key1,inserted.Key2,inserted.Cnt;
go
exec P1 1,5
go
exec P1 1,5
go
exec P1 1,3
go
exec P1 1,5
go

(请注意,它不一定是一个过程,我只是从一个线程中调用它以显示其工作原理)

结果:

Key1        Key2        Cnt
----------- ----------- -----------
1           5           0

Key1        Key2        Cnt
----------- ----------- -----------
1           5           1

Key1        Key2        Cnt
----------- ----------- -----------
1           3           0

Key1        Key2        Cnt
----------- ----------- -----------
1           5           2

即使有多个线程对此进行调用,我相信它也应该对访问进行序列化。我产生的输出只是为了表明每个调用者也可以知道他们将计数器设置为哪个值(在此为column Cnt),即使之后另一个调用者立即更改了该值。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

SQL Server表中的并行插入/更新

来自分类Dev

大并行插入SQL Server表

来自分类Dev

如何在SQL Server并行数据仓库表中插入多行

来自分类Dev

如何找到有关在sql server 2008中更新或插入sql表行的信息?

来自分类Dev

在SQL Server中插入更新数据帮助

来自分类Dev

在SQL Server表中插入对象列表

来自分类Dev

' ' 插入表中的 SQL Server 错误

来自分类Dev

更新/插入触发器触发SQL Server中的相同表

来自分类Dev

使用 SQL 中的其他表更新/插入表

来自分类Dev

在C#中的SQL中插入后更新表

来自分类Dev

在C#中的SQL中插入后更新表

来自分类Dev

SQL Server中更新表的最快方法

来自分类Dev

更新 SQL Server 中的多个表

来自分类Dev

在 SQL Server 中的游标中插入和更新

来自分类Dev

并行查询多个SQL Server表

来自分类Dev

在SQL Server中插入/删除/更新触发器

来自分类Dev

触发在SQL Server中插入,更新,删除库存数量

来自分类Dev

触发在SQL Server中插入,更新,删除库存数量

来自分类Dev

如何从SQL Server的sqlite中插入更新的记录

来自分类Dev

回滚插入到SQL Server 2005中的多个表

来自分类Dev

从其他表在SQL Server中插入数据

来自分类Dev

如何在SQL Server表中插入多个值?

来自分类Dev

从XML将数据插入SQL Server中的表

来自分类Dev

使用Management Studio在表SQL Server中插入文件PDF

来自分类Dev

将XML节点插入SQL Server中的表

来自分类Dev

Microsoft SQL Server每秒将数据插入大表中

来自分类Dev

SQL Server Insert语句在表中插入长文本

来自分类Dev

SQL Server 2008在表中插入缺少日期的新记录

来自分类Dev

插入之前删除SQL Server表中的记录

Related 相关文章

热门标签

归档