我有一个包含三个字段的源表
Declare @tmptvp table
(
ID int,
StartDate Datetime,
EndDate Datetime
)
Insert @tmptvp values(1,'2013-04-28','2013-04-30')
Insert @tmptvp values(2,'2013-05-01','2013-06-30')
select * from @tmptvp
我的目标表是“InsertDate”,包含以下数据。
Insert InsertDate values(1,'2013-04-28','2013-06-30')
while merging
MERGE (@tmptvp) as TGT
USING
(select ID,StartDate,EndDate FROM @tmptvp) AS SRC
ON
(TGT.StartDate = SRC.StartDate OR TGT.EndDate = SRC.EndDate)
WHEN MATCHED THEN
UPDATE SET TGT.StartDate = CASE WHEN SRC.StartDate < TGT.StartDate THEN SRC.StartDate ELSE TGT.StartDate END,
TGT.EndDate = CASE WHEN SRC.EndDate > TGT.EndDate THEN SRC.EndDate ELSE TGT.EndDate END,
WHEN NOT MATCHED THEN
INSERT (ID,StartDate,EndDate)
VALUES
(SRC.ID,SRC.StartDate,SRC.EndDate);
上面的合并语句抛出 MERGE 语句多次尝试更新或删除同一行。当目标行匹配多个源行时会发生这种情况。MERGE 语句不能多次 UPDATE/DELETE 目标表的同一行。优化 ON 子句以确保目标行最多匹配一个源行,或使用 GROUP BY 子句对源行进行分组。