SQL Server Merge matched 再加其他条件的示例

这里介绍使用临时表的方式进行Merge,额外的条件语句用红色标出:

假设有一个字典表 dic_dict {code,name,update_date}
第一步 先创建临时表
create table #temp_source( [code] [varchar](20) COLLATE CHINESE_PRC_CI_AS not null, [name] [varchar](1000) COLLATE CHINESE_PRC_CI_AS not null )
复制代码
第二步 临时表中插入要merge的数据(可以用批量插入)
insert into #temp_source (code,name)values(@code,@name)

第三步 使用merge加其他条件 翻译就是:根据code是否存在进行对比更新。如果存在 同时name不相同的时候 对name进行更新。 如果code不存在 则 执行插入。
merge into dic_dict 
target using #temp_source source
on (target.code = source.code )
when matched
and (target.name != source.name)
then update set target.name = source.name,update_date= GETDATE()
when not matched
then insert (code,name,update_date)
values (source.code,source.name,GETDATE());

第四步 删除临时表
drop table #temp_source
复制代码

 

1
 

  

posted @   歌·颂  阅读(405)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示