2014-02-19 105 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

非常感謝你 –