Solutions for INSERT OR UPDATE on SQL Server

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

    /*
    CREATE TABLE ApplicationsDesSocietes (
       id                   INT IDENTITY(0,1)    NOT NULL,
       applicationId        INT                  NOT NULL,
       societeId            INT                  NOT NULL,
       suppression          BIT                  NULL,
       CONSTRAINT PK_APPLICATIONSDESSOCIETES PRIMARY KEY (id)
    )
    GO
    --*/
    
    DECLARE @applicationId INT = 81, @societeId INT = 43, @suppression BIT = 0
    
    MERGE dbo.ApplicationsDesSocietes WITH (HOLDLOCK) AS target
    --set the SOURCE table one row
    USING (VALUES (@applicationId, @societeId, @suppression))
        AS source (applicationId, societeId, suppression)
        --here goes the ON join condition
        ON target.applicationId = source.applicationId and target.societeId = source.societeId
    WHEN MATCHED THEN
        UPDATE
        --place your list of SET here
        SET target.suppression = source.suppression
    WHEN NOT MATCHED THEN
        --insert a new line with the SOURCE table one row
        INSERT (applicationId, societeId, suppression)
        VALUES (source.applicationId, source.societeId, source.suppression);
    GO
    

    Replace table and field names by whatever you need. Take care of the using ON condition. Then set the appropriate value (and type) for the variables on the DECLARE line.

    Cheers.

提交回复
热议问题