MERGE查询以维护表克隆

时间:2018-09-20 08:30:37

标签: sql sql-server merge

我想在另一个数据库(那里的表名:targettable)上保留特定表(sourcedb..sourcetable)的克隆,以便进行翻版。由于这涉及所有三个insert,delete和update语句,因此我认为我将使用MERGE语句。这里的关键思想是仅基于源表的rowversion列进行数据传输。请记住,目标表具有与源一相同的字段(还有更多),在相同的字段上具有PK,并且所有数据类型都相同(除了rowversion列将为binary(8)之外)源表的rowversion值,而不是其本身的rowversion),我想到了:

WITH live as
(
    select *
    from sourcedb..sourcetable
    where 1=1
        and (........)  -- We don't want rows from the source table that don't meet these criteria
)
MERGE 
    INTO targettable as olap 
    USING live 
    ON olap.PKfield1=live.PKfield1 and olap.PKfield2=live.PKfield2 and .. -- join on all PK fields
    WHEN MATCHED AND live.rowversioncol > olap.rowversioncol then update set
        field1      =   live.field1,
        field2      =   live.field2,
        (...all NON-PK fields....)
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (field1,field2,....(all fields)......) 
        VALUES (field1,field2,....(all fields)......)   
    WHEN NOT MATCHED BY SOURCE THEN
        DELETE

您是否可以确认运行此查询正确地确保目标表具有与源表相同的数据(已删除过滤的行)?

0 个答案:

没有答案