假设表 struct 为MyTable(KEY, datafield1, datafield2...)
.
我经常想更新现有记录,或者在不存在的情况下插入新记录.
基本上:
IF (key exists)
run update command
ELSE
run insert command
写这篇文章最好的方式是什么?
假设表 struct 为MyTable(KEY, datafield1, datafield2...)
.
我经常想更新现有记录,或者在不存在的情况下插入新记录.
基本上:
IF (key exists)
run update command
ELSE
run insert command
写这篇文章最好的方式是什么?
不要忘记交易.性能很好,但很简单(如果存在的话)这种做法非常危险
@Beau Crawf或d&@Esteban展示了总体思路,但容易出错.
为了避免死锁和PK冲突,您可以使用以下方法:
begin tran
if exists (select * from table with (updlock,serializable) where key = @key)
begin
update table set ...
where key = @key
end
else
begin
insert into table (key, ...)
values (@key, ...)
end
commit tran
或
begin tran
update table with (serializable) set ...
where key = @key
if @@rowcount = 0
begin
insert into table (key, ...) values (@key,..)
end
commit tran