这让我对 MSSQL (rant on my blog) 感到恼火。我希望 MSSQL 支持 upsert。
@Dillie-O 的代码在旧 SQL 版本中是一个好方法(+1 票),但它仍然基本上是两个 IO 操作(exists 然后update 或insert)
this post 上有一个稍微好一点的方法,基本上:
--try an update
update tablename
set field1 = 'new value',
field2 = 'different value',
...
where idfield = 7
--insert if failed
if @@rowcount = 0 and @@error = 0
insert into tablename
( idfield, field1, field2, ... )
values ( 7, 'value one', 'another value', ... )
如果是更新,则将其减少到一个 IO 操作,如果是插入,则将其减少到两个。
MS Sql2008 从 SQL:2003 标准引入merge:
merge tablename as target
using (values ('new value', 'different value'))
as source (field1, field2)
on target.idfield = 7
when matched then
update
set field1 = source.field1,
field2 = source.field2,
...
when not matched then
insert ( idfield, field1, field2, ... )
values ( 7, source.field1, source.field2, ... )
现在它实际上只是一个 IO 操作,但是代码很糟糕:-(