Solutions for INSERT OR UPDATE on SQL Server

后端 未结 22 2475
别跟我提以往
别跟我提以往 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 23:00

    Do an UPSERT:

    UPDATE MyTable SET FieldA=@FieldA WHERE Key=@Key
    
    IF @@ROWCOUNT = 0
       INSERT INTO MyTable (FieldA) VALUES (@FieldA)
    

    http://en.wikipedia.org/wiki/Upsert

提交回复
热议问题