如何比较2个表,删除旧记录并添加新记录sql

时间:2013-02-25 10:14:17

标签: sql database sql-server-2008 comparison

我有两个完全相同格式的sql表,1个用作临时表,1个用作静态表。

目前我的代码只是擦除静态表并每次使用临时表中的新数据填充它,但这不是我需要的。我正在尝试创建某种类型的sql diff来比较2个表,然后删除不在临时表中但在静态表中的记录,它将添加临时表中的新记录但是不是静态表。因此静态表只在每次运行时更新,而不是擦除和重写。

所以如果我的临时表有:ABC1,ABC2,ABC4 我的静态表有:ABC1,ABC3,ABC4

我的sql查询理想情况下会返回:ABC1,ABC2,ABC4

我有两个查询,似乎选择了我想要删除的值和我要添加的值,但我目前无法让删除一个正常运行,所以我想知道是否有一些我缺少的东西查询。

此查询插入临时表中的数据,但不插入静态表:

 Insert into [static table] 
    SELECT * 
  FROM [temp table]

EXCEPT

SELECT *
  FROM [static table]

此查询应删除静态表中的数据,但不删除临时表中的数据:

 delete from [static table] 
 where not exists 
    (SELECT *
  FROM [static table]

EXCEPT

SELECT *
  FROM [temp table] )

任何人都可以建议我的查询问题是什么,或者是否有更好的方法来执行此任务?感谢

3 个答案:

答案 0 :(得分:2)

查看SQL 2008中引入的MERGE

e.g。未经测试,但有点类似......

MERGE StaticTable AS target
USING TempTable AS source ON target.ColumnA = source.ColumnA
-- value doesn't exist in the target table, so add it
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (ColumnA) VALUES (source.ColumnA)
-- value doesn't exist in the source table, so delete from target
WHEN NOT MATCHED BY SOURCE THEN 
    DELETE

编辑:要处理多个列,例如:

 MERGE StaticTable AS target
    USING TempTable AS source ON target.ColumnA = source.ColumnA 
        AND target.ColumnB = source.ColumnB
    -- value doesn't exist in the target table, so add it
    WHEN NOT MATCHED BY TARGET THEN 
        INSERT (ColumnA, ColumnB) VALUES (source.ColumnA, source.ColumnB)
    -- value doesn't exist in the source table, so delete from target
    WHEN NOT MATCHED BY SOURCE THEN 
        DELETE

答案 1 :(得分:1)

我猜'合并'应该做你想要的。 以下是详细信息: http://msdn.microsoft.com/en-us/library/bb522522(v=sql.105).aspx

答案 2 :(得分:0)

如果您的表具有任何已定义的唯一键,则可以使用IN语法:

DELETE FROM static WHERE id NOT IN(SELECT id from temporary);
INSERT INTO static WHERE id IN(SELECT id from temporary) AND NOT id IN (SELECT id from static);
相关问题