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

问题描述 投票:0回答:1
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')

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

sql-server sql-server-2005 sql-server-express exists race-condition
1个回答
1
投票

你可以使用transaction。确保在单个事务中锁定所有必需的表,然后释放它们。

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

如果您有多个,也可以为您的交易命名。

© www.soinside.com 2019 - 2024. All rights reserved.