如果记录存在则插入并更新,否则竞争条件

发布于 2024-11-01 19:41:44 字数 264 浏览 10 评论 0原文

if exists (select itemcode from item where itemcode=1120)
update item 
set itemname = 'laptop'
where itemcode = 1120

else 
insert into item (itemcode,itemname)
values (1120,'laptop')

它将被多个用户使用。这个查询会给出竞争条件吗? 如果是,那么如何?我应该用什么来代替这个查询?

if exists (select itemcode from item where itemcode=1120)
update item 
set itemname = 'laptop'
where itemcode = 1120

else 
insert into item (itemcode,itemname)
values (1120,'laptop')

it will be used by multiple users. will this query give a race condition.
if yes, then how?what shall i use in place of this query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

且行且努力 2024-11-08 19:41:44

您可以为此使用交易。确保在单个事务中锁定所有所需的表,然后释放它们。

begin transaction

begin try

    if exists (select itemcode from item where itemcode=1120)
    BEGIN
    update item 
    set itemname = 'laptop'
    where itemcode = 1120
    END

    else 
    BEGIN
    insert into item (itemcode,itemname)
    values (1120,'laptop')
    END

    commit transaction

end try

begin catch
  raiserror('Message here', 16, 1)
  rollback transaction
end catch

如果您有多个交易,您还可以为您的交易指定名称。

You may use transaction for this. Make sure to lock all your required tables in single transaction then release them.

begin transaction

begin try

    if exists (select itemcode from item where itemcode=1120)
    BEGIN
    update item 
    set itemname = 'laptop'
    where itemcode = 1120
    END

    else 
    BEGIN
    insert into item (itemcode,itemname)
    values (1120,'laptop')
    END

    commit transaction

end try

begin catch
  raiserror('Message here', 16, 1)
  rollback transaction
end catch

You can also give name to your transaction if you have multiple.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文