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')
它将被多个用户使用。这个查询会给出竞争条件。如果是,那怎么样?我将用什么来代替这个查询?
你可以使用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
如果您有多个,也可以为您的交易命名。