【SQL server】merge 关键字的使用

来源:互联网 发布:mysql时间转日期函数 编辑:程序博客网 时间:2024/05/21 12:50

使用Merge的场景:

  •     数据同步
  •     数据转换
  •     基于源表对目标表做Insert,Update,Delete操作

Merge语法,如下:

merge /* top(2) */into TargetTable As T  --需要更改的数据对象using SourceTable as S --以某数据对象为目标进行查看on T.id = S.id --以什么字段进行比较when Matched --字段比较相等Then update set T.[desc] = S.[desc]  --更新when not matched --字段比较不相等then insert values(s.id,s.[desc]) --插入when not matched by source --目标表存在,原表不存在,则删除目标表不同的数据then deleteoutput $Action As [action],inserted.id as 插入id, --显示操作的视图,$action 显示操作动作inserted.[desc] as 插入的desc,deleted.id as 删除的id,deleted.[desc] as 删除的desc;

另补充insert中output用法:

declare @newrows table(id int,[desc] nvarchar(40));insert into TargetTableoutput inserted.id,inserted.[desc]into @newrows --可不用变量 直接output输出插入的结果select * from SourceTable;select * from @newrows;


原创粉丝点击