如何在sql中更新具有相同id的多个行

时间:2016-10-26 10:10:48

标签: sql-server-2012

这是我的代码: 我在更新行时遇到错误

Declare @XMLDocument XML
set @XMLDocument = 
'<EmployeeZoneMapping>
  <EmployeeZoneData>
   <EmployeeID>5</EmployeeID>
   <ServiceCircleZoneID>3</ServiceCircleZoneID>
   <EmployeeZoneMappingStatus>1</EmployeeZoneMappingStatus>
  </EmployeeZoneData>
 <EmployeeZoneData>
<EmployeeID>5</EmployeeID>
<ServiceCircleZoneID>6</ServiceCircleZoneID>
<EmployeeZoneMappingStatus>0</EmployeeZoneMappingStatus>
  </EmployeeZoneData>
</EmployeeZoneMapping>'

   ;WITH XmlData AS 
(
SELECT
    A.Details_EmployeeZoneMapping.value('(EmployeeID) [1]','int') AS EmployeeID,
  A.Details_EmployeeZoneMapping.value('(ServiceCircleZoneID) [1]','tinyint') AS ServiceCircleZoneID,
  A.Details_EmployeeZoneMapping.value('(EmployeeZoneMappingStatus) [1]','bit') AS EmployeeZoneMappingStatus
from  @XMLDocument.nodes ('EmployeeZoneMapping/EmployeeZoneData') AS  A (Details_EmployeeZoneMapping))
MERGE INTO dbo.Details_EmployeeZoneMapping t 
USING XmlData x ON t.EmployeeID = x.EmployeeID 
WHEN MATCHED 
   THEN 
     UPDATE SET 
    t.ServiceCircleZoneID = x.ServiceCircleZoneID,
   t.EmployeeZoneMappingStatus = x.EmployeeZoneMappingStatus


WHEN NOT MATCHED 
   THEN 
  INSERT(EmployeeID,ServiceCircleZoneID,EmployeeZoneMappingStatus)
  VALUES(x.EmployeeID, x.ServiceCircleZoneID, x.EmployeeZoneMappingStatus)
;

错误:

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

0 个答案:

没有答案