开发者

insert and update if a record exists else not , race condition

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜