在单个SQL语句中插入和更新多个值

时间:2015-08-13 11:39:49

标签: sql

我们正在使用Insert语句进行多次插入:

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")

在上表中,ID是主键,想要知道一个查询并传递所有值,值应更新现有记录并将新记录插入表

1 个答案:

答案 0 :(得分:3)

您可以使用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