我在登台表中有超过一百万行。每月登台表获取行,插入主表后,将删除暂存中的那些行。
还有另一个名为allchanges
的表,它跟踪对主表所做的所有更新(比如month1-address change,month2- phone change,所以所有更改都有2条记录)而master只有一条更新记录。
我将MERGE
用于when matched
,when not matched by target
和when not matched by source
。
WITH NewAndChanged
AS (SELECT TOP 2 stg.[EmpName],
stg.[EmpNumber],
FROM staging AS stg
ORDER BY stg.[EmpNumber]
EXCEPT
SELECT TOP 2 mas.[EmpName],
mas.[EmpNumber],
FROM [Master] AS mas
ORDER BY mas.EmpNumber)
MERGE INTO [Master]
AS Target
USING NewAndChanged AS Source ON Target.EmpNumber = Source.EmpNumber
WHEN MATCHED AND (COALESCE (Target.EmpName, '') <> COALESCE (Source.EmpName, '')
) THEN UPDATE
SET Target.EmpName = Source.EmpName,
WHEN NOT MATCHED BY TARGET THEN INSERT ([EmpName], [EmpNumber])
WHEN NOT MATCHED BY SOURCE AND Target.Active = 1 THEN UPDATE
SET Active = 0
output $action as act;
由于我一次只选择2行,when not matched by source
将第2次迭代中前2行的活动设置为零。我怎么能克服这个?