Sqlserver mereg 合并 Insert、Update、Delete 增删改
CREATE TABLE TestA ( Id INT PRIMARY KEY IDENTITY(1,1), poisId VARCHAR(16) NOT NULL UNIQUE, pName VARCHAR(16) ) INSERT dbo.TestA ( poisId, pName ) VALUES ( 'B031704RPP', -- poisId - varchar(16) '中石化跨世加油站' -- pName - varchar(16) ), ( 'B0FFLCCK9Y', -- poisId - varchar(16) '中国石化加油站' -- pName - varchar(16) ), ( 'B0FFL2TG2I', -- poisId - varchar(16) '奔驰宝马汽车' -- pName - varchar(16) ) MERGE dbo.TestA AS TargetA USING ( SELECT 'B031704RPP' AS poisId, '第一条3次' as pName UNION SELECT 'B0FFGAWMVT' AS poisId, '第四条3次' as pName UNION SELECT 'B0FFLCCK9Y' AS poisId, '第二条3次' as pName UNION SELECT 'B0G0ANQBJR' AS poisId, '百世德' AS pName ) AS source (poidId,pName) ON TargetA.poisId=source.poidId WHEN MATCHED THEN UPDATE SET TargetA.pName=source.pName WHEN NOT MATCHED THEN INSERT (poisId,pName) VALUES(source.poidId,source.pName);
-- 写法二
MERGE dbo.TestA AS TargetA USING ( Values( 'B031704RPP', '第一条3次'), ('B0FFGAWMVT', '第四条3次'), ('B0FFLCCK9Y', '第二条3次') ) AS source (poidId,pName) ON TargetA.poisId=source.poidId WHEN MATCHED THEN UPDATE SET TargetA.pName=source.pName WHEN NOT MATCHED THEN INSERT (poisId,pName) VALUES(source.poidId,source.pName);
官方文档地址 https://docs.microsoft.com/zh-cn/sql/t-sql/statements/merge-transact-sql?view=sql-server-ver15 参考地址 https://blog.csdn.net/qq_27628011/article/details/89319710