Solutions for INSERT OR UPDATE on SQL Server

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

    Doing an if exists ... else ... involves doing two requests minimum (one to check, one to take action). The following approach requires only one where the record exists, two if an insert is required:

    DECLARE @RowExists bit
    SET @RowExists = 0
    UPDATE MyTable SET DataField1 = 'xxx', @RowExists = 1 WHERE Key = 123
    IF @RowExists = 0
      INSERT INTO MyTable (Key, DataField1) VALUES (123, 'xxx')
    

提交回复
热议问题