码迷,mamicode.com
首页 > 数据库 > 详细

Sql中的Merge和output

时间:2015-06-30 10:15:06      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

先看merge,

不用merge时:

--更新
update TA
    set ColA=isnull((select top 1 Value from TB where TB.UserId=TA.UserId and TB.TypeName=@val),0)
    where DATEDIFF(day,[Date],@day)=0
--插入没有的数据
insert into TA 
    select newid(),UserId,@day,0,0,Value from TB 
    where not exists (select UserId from TA where TA.UserId=TB.UserId and DATEDIFF(day,[Date],@day)=0) 
        and TypeName=@val

用Merge:

merge TA as a
using (select * from TB where TypeName=@val) as b
on b.UserId=a.UserId
when matched then update set a.ColA=b.Value
when not matched then insert values(newid(),UserId,@day,0,0,Value)
when not matched by source then update set a.ColA=0;

 

Sql中的Merge和output

标签:

原文地址:http://www.cnblogs.com/icyJ/p/4609561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!