2014-02-19 61 views
0

我有两个表,并希望插入或更新从tableA到TableB chages。如何在merge语句的`when`子句中使用条件?

PatientIdComposeId两个表

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

我认为您在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相匹配的要求,在您的ON条款中指定。因此,在这里的附加条件中对target的任何引用都不可能起作用。

+0

非常感谢你 –