标签:table 版本 arch The style int 一个 -- code
USE tempdb; GO IF OBJECT_ID(‘SourceTable‘) IS NOT NULL DROP TABLE SourceTable; IF OBJECT_ID(‘TargetTable‘) IS NOT NULL DROP TABLE TargetTable; --源 CREATE TABLE SourceTable ( id INT, name VARCHAR(2), [desc] NVARCHAR(50) ); --目标 CREATE TABLE TargetTable ( id INT, name VARCHAR(2), [desc] NVARCHAR(50) ); --源表数据 INSERT INTO SourceTable VALUES (1, ‘a‘, ‘描述1‘), (2, ‘a‘, ‘描述2‘), (3, ‘a‘, ‘描述3‘), (4, ‘a‘, ‘描述4‘); --目标表数据 INSERT INTO TargetTable VALUES (1, ‘a‘, ‘在源表里存在,将会被更新‘); INSERT INTO TargetTable VALUES (2, ‘a‘, ‘在源表里存在,将会被更新‘); INSERT INTO TargetTable VALUES (5, ‘a‘, ‘在源表里不存在,将会被删除‘); INSERT INTO TargetTable VALUES (6, ‘b‘, ‘在源表里不存在,但是条件不符合,不删除‘); SELECT * FROM SourceTable AS st; /* id name desc 1 a 描述1 2 a 描述2 3 a 描述3 4 a 描述4 */ SELECT * FROM TargetTable AS tt; /* id name desc 1 a 在源表里存在,将会被更新 2 a 在源表里存在,将会被更新 5 a 在源表里不存在,将会被删除 6 b 在源表里不存在,但是条件不符合,不删除 */ --注意事项 --1.最后的分号必须有 --2.源表可以是一个具体的表,也可以是一个子查询语句 --3.2008或以上版本才有的功能 MERGE INTO TargetTable AS T --可添加 TOP 限制操作行数: MERGE TOP(2) USING SourceTable AS S ON T.id = S.id AND T.name = ‘a‘ AND S.name = ‘a‘ WHEN MATCHED --当两者的id能匹配,id=1,2的数据被更新 THEN UPDATE SET T.[desc] = S.[desc] WHEN NOT MATCHED --目标表没有的ID, 在原表中有,则插入相关的数据 THEN INSERT (id,name) VALUES (S.id, S.name) WHEN NOT MATCHED BY SOURCE AND t.name = ‘a‘ --目标表中存在,源表不存在,则删除 THEN DELETE OUTPUT $ACTION AS [Action], INSERTED.id AS [插入的id], Inserted.name AS [插入的name], INSERTED.[desc] AS [插入的DESC], DELETED.id AS [删除的id], DELETED.name AS [删除的name], DELETED.[desc] AS [删除的DESC]; SELECT * FROM SourceTable AS st; SELECT * FROM TargetTable AS tt;
标签:table 版本 arch The style int 一个 -- code
原文地址:https://www.cnblogs.com/BinBinGo/p/10576575.html