我有两个表,想要从tableA到TableB插入或更新chages。
PatientId
和ComposeId
是两个表中的复合键
table A
PatientId
ComposeId
Name
Family
table B
PatientId
ComposeId
Name
Family
我想实现类似这样的东西或尽可能使用嵌套合并。怎么做?
Merge TbleB as Target
using (select PatientId,Compseid,Name,Family from TableA) as source
on (source.PatientId=target.PatientId and source.ComposeId=target.Composeid and source.Name=Target.Name
and Source.Family=target.Family)
when not matched and source.patientId=target.PatientId and Source.CompositionId=Target.CompistionId
then update
set Name=Source.Name,
set Family=Source.Family
when not matched and (source.patientId<>target.PatientId and Source.CompositionId<>Target.CompistionId) then
Insert
答案 0 :(得分:0)
我认为您在ON
条款中放置了太多条件。我想你只想要:
Merge TbleB as Target
using (select PatientId,Compseid,Name,Family from TableA) as source
on source.PatientId=target.PatientId and source.ComposeId=target.Composeid
when matched --You could add the Name<>Name or Family<>Family WHEN condition here
--if wanted, but I wouldn't bother usually
then update
set Name=Source.Name,
set Family=Source.Family
when not matched then
Insert
要指出的是,以下内容没有任何意义:
when not matched and source.patientId=target.PatientId and Source.CompositionId=Target.CompistionId
when not matched
表示target
中的 no 行符合ON
子句中指定的要求。因此,在此处附加条件中对target
的任何引用都可能无效。