1

We are using Insert statements for multi inserts like this:

INSERT INTO [db1].[dbo].[tb1] ([ID], [CLM1], [CLM2]) 
VALUES 
('1', "A", "DB"),
('2', "AB", "BQ"),
('3', "AA", "BH"),
('4', "AD", "BT"),
('5', "AF", "EB"),
('6', "EA", "AB")

In the above table, ID is primary key, want to know one query with passing all values, values should update existing records and insert new records into table

2
  • 1
    SQL Server? Which version? Commented Aug 13, 2015 at 11:40
  • 2
    For SQL Server there is the MERGE command... but it is a pain... Commented Aug 13, 2015 at 11:43

1 Answer 1

3

You can use Merge:

MERGE INTO [db1].[dbo].[tb1] AS Target
USING (
    VALUES 
    ('1', 'A', 'DB'), 
    ('2', 'AB', 'BQ'), 
    ('3', 'AA', 'BH'), 
    ('4', 'AD', 'BT'), 
    ('5', 'AF', 'EB'), 
    ('6', 'EA', 'AB')
) AS Source (new_ID, new_CLM1, new_CLM2)
ON Target.ID = Source.new_ID
WHEN MATCHED THEN
UPDATE SET 
    ID = Source.new_ID,
    CLM1 = Source.new_CLM1,
    CLM2 = Source.new_CLM2
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, CLM1, CLM2) VALUES (new_ID, new_CLM1, new_CLM2);

Merge Doc

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much, its working exactly how we wanted to be, thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.