Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert or Update multiple rows in Sql Server

I need to execute a query as shown below. Columns KEY1 and KEY2 are keys that cannot be repeated. If there are keys matching, I need to perform an update VAL instead of insert. How can I do that in Sql Server?

INSERT INTO tableA
  ( 
      KEY1,
      KEY2,
      VAL,                      
  ) VALUES (
          -- Row A
          'datakeyA1',
          'datakeyA2',
          'somevaluetoinsertorupdate'
      ) , (
          -- Row B
          'datakeyB1',
          'datakeyB2',
          'somevaluetoinsertorupdate'
      ) , (
          -- Row C
          'datakeyC1',
          'datakeyC2',
          'somevaluetoinsertorupdate'
      );

I tried using MERGE, but looking at the syntax, I am not sure if it supports updating / inserting multiple rows. If anyone has encountered a similar situation in the past, could you please help out?

EDIT:

If I were using MySql, I would have just used:

ON DUPLICATE KEY UPDATE 
 VAL = VALUES(VAL)

in the query.

like image 243
softwarematter Avatar asked Mar 05 '26 18:03

softwarematter


1 Answers

You can use a table value constructor as the source table to make this work with MERGE:

MERGE tableA AS t
USING (VALUES 
        ('datakeyA1', 'datakeyA2', 'somevaluetoinsertorupdate'), 
        ('datakeyB1', 'datakeyB2', 'somevaluetoinsertorupdate'),
        ('datakeyC1', 'datakeyC2', 'somevaluetoinsertorupdate')
    ) AS s (Key1, Key2, Val)
        ON s.Key1 = t.Key1
        AND s.Key2 = t.Key2
WHEN MATCHED THEN 
    UPDATE 
    SET    Val = s.Val
WHEN NOT MATCHED THEN 
    INSERT (Key1, Key2, Val)
    VALUES (s.Key1, s.Key2, s.Val);
like image 89
GarethD Avatar answered Mar 07 '26 07:03

GarethD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!