SQL合并问题-更新与源不匹配

时间:2019-01-30 10:51:35

标签: sql-server tsql sql-merge

我有一个存储过程,它合并了本地临时表和现有表。

ALTER PROCEDURE [dbo].[SyncProductVariantsFromServices]

    @Items  ProductVariantsTable readonly

AS
BEGIN



CREATE TABLE #ProductVariantsTemp
(
   ItemCode nvarchar(10) collate SQL_Latin1_General_CP1_CI_AS,
   VariantCode nvarchar(10) collate SQL_Latin1_General_CP1_CI_AS,
   VariantDescriptionBG nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS,
   VariantDescriptionEN nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS
)

insert into #ProductVariantsTemp 
select ItemCode, VariantCode, VariantDescriptionBG, VariantDescriptionEN 
 from @Items 


    MERGE ProductVariants AS TARGET
    USING #ProductVariantsTemp AS SOURCE 
    ON (TARGET.ItemCode = SOURCE.ItemCode AND TARGET.VariantCode= SOURCE.VariantCode) 


        WHEN NOT MATCHED BY TARGET THEN  

        INSERT (ItemCode, VariantCode,  VariantDescriptionBG, VariantDescriptionEN) 
        VALUES (SOURCE.ItemCode, SOURCE.VariantCode, SOURCE.VariantDescriptionBG, SOURCE.VariantDescriptionEN)


    OUTPUT INSERTED.ItemCode, INSERTED.VariantCode,  GETDATE() INTO SyncLog;

问题是-我知道在输出子句中,如果未按源合并,我有权访问插入或删除的记录。但是如果“未按源合并”,我想更新

Update  ProductVariants  Set Active = 0 
// when not matched by source

最有效的方法是什么?

2 个答案:

答案 0 :(得分:0)

当您要删除不在目标表中的记录时,必须使用`WHEN NOT MATCHED BY SOURCE'。如果要“停用”记录,则必须在“ MATCHED”子句添加例外时完成此操作。

如果您想保留使用“缓慢变化的维数”进行评估的记录历史记录,我给您提供一些示例,供Kimball用于处理历史数据。

Slowly Changing Dimensions - Part 1

Slowly Changing Dimensions - Part 2

答案 1 :(得分:0)

WHEN NOT MATCHED BY SOURCE的{​​{1}}子句与MERGE语句一起使用。

UPDATE

由于MERGE ProductVariants AS TARGET USING #ProductVariantsTemp AS SOURCE ON (TARGET.ItemCode = SOURCE.ItemCode AND TARGET.VariantCode= SOURCE.VariantCode) WHEN NOT MATCHED BY TARGET THEN INSERT (ItemCode, VariantCode, VariantDescriptionBG, VariantDescriptionEN) VALUES (SOURCE.ItemCode, SOURCE.VariantCode, SOURCE.VariantDescriptionBG, SOURCE.VariantDescriptionEN) WHEN NOT MATCHED BY SOURCE THEN UPDATE SET Active = 0 OUTPUT INSERTED.ItemCode, INSERTED.VariantCode, GETDATE() INTO SyncLog; 表的OUTPUT子句现在可能会返回插入或更新的记录,因此您可以添加特殊列INSERTED,它将告诉您原始操作为{{1 }}或$action。不过,必须更改INSERT表才能接收此值。

UPDATE