zoukankan      html  css  js  c++  java
  • 存在即更新反之插入的三种防唯一键冲突和死锁的写法

    存在即更新,反之插入的需求是很常见的,很多人没有注意并发的问题,高并发下为了避免唯一键冲突和死锁情况,下面提供三种写法,最后一个是sql server 2008及以后版本适用。

    示例表为:

    use tempdb
    go
    create table tb_1 (id int identity primary key,a varchar(50),dt datetime default getdate())
    go

    写法一:

    begin tran
        if exists (select * from tb_1 with (updlock,serializablewhere id=100)
        begin
            update tb_1 set a='a100' where id=100
        end
        else
        begin
            insert tb_1 (a) values ('a100')
        end
    commit tran

    写法二:

    begin tran
        update tb_1 with (serializableset a='a100' where id = 100
        if @@rowcount = 0
        begin
            insert tb_1 (a) values ('a100')
        end
    commit tran

    写法三:

    begin tran
        merge tb_1 with(serializableas a
        using(select 100 as id) as b on a.id=b.id
        when matched then update set a='a100' when not matched then insert (a) values ('a100');
    commit tran


    作者:nzperfect
    出处:http://www.cnblogs.com/nzperfect/
    引用或者转载本BLOG的文章请注明原作者和出处,并保留原文章中的版权信息。

  • 相关阅读:
    hdu 5833 Zhu and 772002 (高斯消元)
    1203事件对象
    作用域面试题
    1130 JS高级 面向对象
    1122JS中级复习
    1120浏览器对象模型 函数分析
    1119动画和复习
    1114面试题作用域
    1113Js操作CSS样式
    1112函数封装和元素的属性
  • 原文地址:https://www.cnblogs.com/nzperfect/p/2193143.html
Copyright © 2011-2022 走看看