Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如果记录存在,则插入并更新,否则,竞争条件_Sql Server_Sql Server 2005_Sql Server Express_Exists_Race Condition - Fatal编程技术网

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

Sql server 如果记录存在,则插入并更新,否则,竞争条件,sql-server,sql-server-2005,sql-server-express,exists,race-condition,Sql Server,Sql Server 2005,Sql Server Express,Exists,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 (

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

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

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')

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

可能的副本也可以读取。实际上,我链接到的副本不是真正的副本。我看到您正在执行
向上插入
。是的,会有比赛条件。在SQLServer2008中,您将使用
Merge
。2005年见@AndersUP-是的,我也发现了这一点,并在
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