0

我在临时表中有超过一百万行。每个月登台表都会获取行,并且在插入主表后,登台中的那些行将被删除。

还有一个名为的表allchanges跟踪对主表所做的所有更新(例如月 1-地址更改,月 2-电话更改,因此所有更改都有 2 条记录),而主表只有一条更新记录。

MERGEwhen matched,when not matched by targetwhen 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 行的 active 设置为零。我怎样才能克服这个?

4

0 回答 0