这让我很不喜欢MSSQL(博客上的rant)。我希望MSSQL受支持
upsert。
@ Dillie-O的代码在较旧的SQL版本(+1票)中是个好方法,但它基本上仍然是两个IO操作(the
exists然后the
update或
insert)。
基本上,这篇文章有一个更好的方法:
--try an updateupdate tablename set field1 = 'new value', field2 = 'different value', ...where idfield = 7--insert if failedif @@rowcount = 0 and @@error = 0 insert into tablename ( idfield, field1, field2, ... ) values ( 7, 'value one', 'another value', ... )
如果是更新,则减少为一个IO操作,如果是插入则为两个。
MS Sql2008
merge从SQL:2003标准引入:
merge tablename as targetusing (values ('new value', 'different value')) as source (field1, field2) on target.idfield = 7when 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操作,但是代码很糟糕:-(



