TSQL 仅将新内容复制到存档 Table

TSQL Copy New Contents to Archive Table Only

我有一个 ArchiveTable,我想定期从 OriginalTable 复制任何新记录。这是我认为可能有用的方法。

INSERT INTO OriginalTable 
    SELECT * 
    FROM ArchiveTable 
    WHERE NOT EXISTS (SELECT * 
                      FROM OriginalTable ot 
                      INNER JOIN ArchiveTable at ON ot.email = at.email)

简单地做一些像..

INSERT INTO ArchiveTable 
    SELECT * FROM OriginalTable

当然,只适用于初始副本。

您当前的查询:

INSERT INTO OriginalTable 
SELECT * FROM ArchiveTable 
WHERE NOT EXISTS 
(SELECT * FROM OriginalTable ot 
INNER JOIN ArchiveTable at 
ON ot.email = at.email)

使用与外部查询无关的 EXISTS 子查询。所以它说,"if no row exists in the original table that has the same email as any row in the archive table, then insert everything in the archive table into the Original table."

可能不是你想要的。您可能想要插入原始 table 中尚不存在的特定行。因此,您可能希望将子查询与外部查询相关联:

INSERT INTO OriginalTable  
SELECT * FROM ArchiveTable at
WHERE NOT EXISTS 
(SELECT * FROM OriginalTable ot 
WHERE ot.email = at.email)

这个查询说,"insert into the original table, any rows in the archive table where I don't already have the Email in the Original table"。