MERGE同步
CREATE TABLE Product
(
ProductID VARCHAR(7) NOT NULL
PRIMARY KEY ,
ProductName VARCHAR(100) NOT NULL ,
age int DEFAULT 0
) ;
INSERT INTO Product
VALUES ( '11', '周杰伦', 50 ),
( '12', '周星驰', 30 ) ;
--目标表
CREATE TABLE ProductNew
(
ProductID VARCHAR(7) NOT NULL
PRIMARY KEY ,
ProductName VARCHAR(100) NOT NULL ,
age int DEFAULT 0
) ;
INSERT INTO ProductNew
VALUES ( '11', '周杰伦', 50 ),
( '13', '成龙', 30 ) ;
SELECT * FROM ProductNew
SELECT * FROM Product
MERGE ProductNew AS d
USING Product AS s
ON s.ProductID = d.ProductId
WHEN NOT MATCHED BY TARGET
THEN
INSERT (
ProductID ,
ProductName ,
age
)
VALUES
( s.ProductID ,
s.ProductName ,
s.age
)
--WHEN NOT MATCHED BY SOURCE
-- THEN
--DELETE
WHEN MATCHED
THEN
UPDATE
SET
d.ProductName = s.ProductName ,
d.age = s.age ;
SELECT * FROM ProductNew
SELECT * FROM Product
return
DROP TABLE Product
DROP TABLE ProductNew
/*
ProductID ProductName age
11 周杰伦 50
13 成龙 30
ProductID ProductName age
11 周杰伦 50
12 周星驰 30
ProductID ProductName age
11 周杰伦 50
12 周星驰 30
13 成龙 30
ProductID ProductName age
11 周杰伦 50
12 周星驰 30
*/