Solutions for INSERT OR UPDATE on SQL Server

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

    You can use this query. Work in all SQL Server editions. It's simple, and clear. But you need use 2 queries. You can use if you can't use MERGE

        BEGIN TRAN
    
        UPDATE table
        SET Id = @ID, Description = @Description
        WHERE Id = @Id
    
        INSERT INTO table(Id, Description)
        SELECT @Id, @Description
        WHERE NOT EXISTS (SELECT NULL FROM table WHERE Id = @Id)
    
        COMMIT TRAN
    

    NOTE: Please explain answer negatives

提交回复
热议问题