如何在merge语句中使用`when`子句中的条件?

时间:2014-02-19 07:40:09

标签: sql-server sql-server-2008 sql-server-2012

我有两个表,想要从tableA到TableB插入或更新chages。

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

1 个答案:

答案 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的任何引用都可能无效。