Solutions for INSERT OR UPDATE on SQL Server

后端 未结 22 1976
别跟我提以往
别跟我提以往 2020-11-21 22:23

Assume a table structure of MyTable(KEY, datafield1, datafield2...).

Often I want to either update an existing record, or insert a new record if it does

22条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 22:56

    See my detailed answer to a very similar previous question

    @Beau Crawford's is a good way in SQL 2005 and below, though if you're granting rep it should go to the first guy to SO it. The only problem is that for inserts it's still two IO operations.

    MS Sql2008 introduces merge from the SQL:2003 standard:

    merge tablename with(HOLDLOCK) 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, ... )
    

    Now it's really just one IO operation, but awful code :-(

提交回复
热议问题