我正在将数据从表复制到另一个表。我想知道维护数据完整性和性能会更好。
步骤:
发件人
INSERT INTO archive
SELECT * FROM logs
WHERE datediff(day, logs.timestamp, GetDate()) > @day
DELETE logsf FROM logs As logsf
INNER JOIN archive as archivef ON logsf.uuid = archivef.uuid
WHERE datediff(day, logsf.timestamp, GetDate()) > @jour
要
INSERT INTO archive
SELECT * FROM logs
WHERE datediff(day, logs.timestamp, GetDate()) > @day
AND NOT EXISTS (
SELECT * FROM archive
WHERE datediff(day, logs.timestamp, GetDate()) > @day
)
DELETE logsf FROM logs As logsf
INNER JOIN archive as archivef ON logsf.uuid = archivef.uuid
WHERE datediff(day, logsf.timestamp, GetDate()) > @jour
你会使用哪一个:
如果不存在则插入+存在时删除(独立)
或
如果没有错误(交易),则插入和删除 或
结合两者
为什么?
答案 0 :(得分:2)
使用SQL Server,您可以使用output clause将已删除的项目直接放入存档表中:
DELETE logs
OUTPUT deleted.* INTO archive
WHERE datediff(day, timestamp, GetDate()) > @jour
答案 1 :(得分:1)
我会使用选项2,因为它会更快,因为SQL不太复杂。
我更喜欢在事务中包装它的想法,以便在出现任何错误时进行回滚。