Sql中的Merge和output

时间:2023-03-10 07:11:27
Sql中的Merge和output

先看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;