merge into
--Merge 简单应用: --1、以另一个表作为源表: ---创建源表 Create Table OriginTable(id Int,caption VarChar(50)) ---创建操作表 Create Table TargetTable(id Int,caption VarChar(50)) --插入测试数据 Insert Into dbo.OriginTable(id,caption)VALUES(1,'测试1') Insert Into dbo.OriginTable(id,caption)VALUES(2,'测试2') Insert Into dbo.OriginTable(id,caption)VALUES(3,'测试3') Insert Into dbo.OriginTable(id,caption)VALUES(4,'测试4') Insert Into dbo.TargetTable(id,caption)VALUES(1,'目标表匹配到了源表则update1') Insert Into dbo.TargetTable(id,caption)VALUES(3,'目标表匹配到了源表则update2') Insert Into dbo.TargetTable(id,caption)VALUES(5,'源表里不存在则delete') Insert Into dbo.TargetTable(id,caption)VALUES(8,'源表里不存在则delete') Select * from OriginTable Select * from TargetTable MERGE INTO TargetTable as T USING OriginTable as S ON T.id=S.id WHEN MATCHED --当上面on后的T.id=S.id时,则更新,也可以加上自定义的限制条件 MATCHED AND S.id=2 Then UpDate set T.caption=S.caption When Not Matched --目标中没有的id ,在源表中有则插入 Then Insert Values(S.id,S.caption) When Not Matched By SOURCE --目标表中存在源表中不存在则删除 Then Delete;--Merge的最后结尾必须是以分号结束的,不能忘了分号 谨记:语法严格要求关键字之间只能有一个英文空格,不能有多余的空格