Equivalent of MySQL ON DUPLICATE KEY UPDATE in Sql Server

后端 未结 5 1097
走了就别回头了
走了就别回头了 2020-12-03 04:41

I am trying to find an equivalent of the following MySql query in Sql Server (2012)?

INSERT INTO mytable (COL_A, COL_B, COL_C, COL_D)
VALUES ( \'VAL_A\',\'VA         


        
5条回答
  •  离开以前
    2020-12-03 05:34

    Stored Procedure will save the day.

    Here I assume that COL_A and COL_B are unique columns and are type of INT NB! Don't have sql-server instance ATM so cannot guarantee correctness of the syntax. UPDATE! Here is a link to SQLFIDDLE

     CREATE TABLE mytable
    (
    COL_A int UNIQUE,
    COL_B int UNIQUE,
    COL_C int,
    COL_D int,
    )
    
    GO
    
    INSERT INTO mytable (COL_A, COL_B, COL_C, COL_D)
    VALUES (1,1,1,1),
    (2,2,2,2),
    (3,3,3,3),
    (4,4,4,4);
    GO
    
    CREATE PROCEDURE updateDuplicate(@COL_A INT, @COL_B INT, @COL_C INT, @COL_D INT)
    AS
    BEGIN
        DECLARE @ret INT
        SELECT @ret = COUNT(*) 
        FROM mytable p 
        WHERE p.COL_A = @COL_A 
            AND p.COL_B = @COL_B
    
         IF (@ret = 0) 
            INSERT INTO mytable (COL_A, COL_B, COL_C, COL_D)
            VALUES ( @COL_A, @COL_B, @COL_C, @COL_D)
    
         IF (@ret > 0)
            UPDATE mytable SET COL_D = @COL_D WHERE col_A = @COL_A AND COL_B = @COL_B  
    END;
    GO
    

    Then call this procedure with needed values instead of Update statement

    exec updateDuplicate 1, 1, 1, 2
    GO
    SELECT * from mytable
    GO
    

提交回复
热议问题