MERGE语句尝试更多>一次更新或删除同一行

时间:2017-11-26 17:08:09

标签: sql sql-server sql-server-2016

我想从源表中进行合并:

CreditAdvisorId SourceId    AddressID   AddressTypeId   CreditAdvisorAddressId  PersonTypeID    CountryId
14951   1   21311   1   36086   4   1
14951   1   21311   1   36086   4   1
14981   1   25773   1   NULL    4   1

进入目标表,看起来像:

CreditAdvisorAddressId  CreditAdvisorId AddressTypeId   PersonTypeID    AddressId   SourceId    CountryId   Created Modified    BeginDate   EndDate
0   6687    1   4   275479  1   1   2017-10-19 10:25:21.260 2017-10-19 10:25:21.260 2017-10-19 08:25:21.2605182 9999-12-31 23:59:59.9999999
1   5429    1   4   275479  1   1   2017-10-19 10:25:21.260 2017-10-19 10:25:21.260 2017-10-19 08:25:21.2605182 9999-12-31 23:59:59.9999999
2   2577    1   4   275490  1   1   2017-10-19 10:25:21.260 2017-10-19 10:25:21.260 2017-10-19 08:25:21.2605182 9999-12-31 23:59:59.9999999

我试过了:

MERGE [dim].[CreditAdvisorAddress] a
USING [stg].[CreditAdvisorAddress] b ON a.[CreditAdvisorAddressID] = b.[CreditAdvisorAddressID] 
                                     AND a.[SourceID] = b.[SourceID] 
                                     AND a.[CountryID] = b.[CountryID]

WHEN NOT MATCHED BY TARGET THEN
    INSERT ([CreditAdvisorId], [AddressTypeId], [PersonTypeID], [AddressId],
            [SourceId], [CountryId], [Created], [Modified])
    VALUES (b.[CreditAdvisorId], b.[AddressTypeId], b.[PersonTypeID], b.[AddressId],
            b.[SourceId], b.[CountryId], @now, @now)

WHEN MATCHED 
     AND a.[CreditAdvisorId] <> b.[CreditAdvisorId]
      OR a.[AddressTypeId] <> b.[AddressTypeId]
      OR a.[PersonTypeID] <> b.[PersonTypeID]
      OR a.[AddressId] <> b.[AddressId]
      --OR a.[SourceId] <> b.[SourceId]
      --OR a.[CountryId] <> b.[CountryId]
    THEN
        UPDATE 
           SET a.[CreditAdvisorId] = b.[CreditAdvisorId],
               a.[AddressTypeId] = b.[AddressTypeId],
               a.[PersonTypeID] = b.[PersonTypeID],
               a.[AddressId] = b.[AddressId],
               a.[SourceId] = b.[SourceId],
               a.[CountryId] = b.[CountryId],
               a.[Modified] = @now

OUTPUT $Action INTO @Summary;

这会返回错误:

  

MERGE语句尝试多次更新或删除同一行。当目标行与多个源行匹配时会发生这种情况。 MERGE语句不能多次更新/删除目标表的同一行。优化ON子句以确保目标行最多匹配一个源行,或使用GROUP BY子句对源行进行分组。

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

错误消息会引导您修改ON statement。您应该插入更多条件以执行表之间的一对一行匹配。所以;也许你也可以添加AddressId;

USING [stg].[CreditAdvisorAddress] b ON a.[CreditAdvisorAddressID] = b.[CreditAdvisorAddressID] AND a.[SourceID] = b.[SourceID] AND a.[CountryID] = b.[CountryID] AND a.[AddressId] = b.[AddressId]