gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:14:59 25 4
gpt4 key购买 nike

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

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

如果我的临时表有:ABC1、ABC2、ABC4我的静态表有:ABC1、ABC3、ABC4

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

我有 2 个查询似乎选择了我想删除的值和我想添加的值,但我目前无法让删除的值正常运行,所以我想知道我是否遗漏了什么查询。

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

 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] )

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

最佳答案

看看MERGE这是在 SQL 2008 中引入的。

例如未经测试,但类似...

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

关于sql - 如何比较2个表,删除旧记录并添加新记录sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15064591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com