Merge子句
把源数据合并到目标表
点击查看代码
CREATE TABLE a
(keycol INT PRIMARY KEY,
col1 INT NOT NULL,
col2 INT NOT NULL,
col3 INT NOT NULL);
CREATE TABLE b
(keycol INT PRIMARY KEY,
col1 INT NOT NULL,
col2 INT NOT NULL,
col3 INT NOT NULL);
INSERT INTO a VALUES (1,0,0,0),(2,0,0,0);
INSERT INTO b VALUES (1,1,1,1),(3,3,3,3);
INSERT INTO a VALUES (3,0,0,0),(4,0,0,0);
INSERT INTO b VALUES (4,1,1,1),(5,3,3,3);
SELECT * FROM dbo.a
SELECT * FROM dbo.b
merge a using
b
on a.[keycol]=b.[keycol]
when matched then
update set a.col1=b.col1,a.col2=b.col2,a.col3=b.col3
when not matched then
insert ([keycol],col1,col2,col3) values (b.[keycol],b.col1,b.col2,b.col3)
when NOT matched BY SOURCE
THEN DELETE;