我有一个SQL Server数据库,它在1个月,2个月之后每秒存储一行,而数据库很大,超过100万行。我想知道在数据库自动更新到新数据库后如何备份或删除旧行。
答案 0 :(得分:0)
我使用了几年前为档案馆构建的一种“通用代码”,并且效果很好。我为您做了一些调整。 假定您有一个名为DateRecord的字段,其中包含最后一次添加或修改记录的日期。另外,您具有ProdDB和ArchiveDB,并且ProdDB中的一个表与ArchiveDB中的表具有相同的结构,只是ArchiveDB中的ID不能为IDENTITY,而可以具有UNIQUE索引:
-- Deletes from the Archive if older than one year
DELETE FROM ArchiveDB.dbo.YourTable
WHERE DateDiff(d, DateRecord, GetDate()) > 365
-- Insert into the ArchiveDB table if older than 30 days (set your request here)
INSERT INTO ArchiveDB.dbo.YourTable
SELECT * FROM ProdDB.dbo.YourTable SRC
WHERE DateRecord < DATEADD(d, -30, GETDATE())
AND NOT EXISTS (
SELECT 1 FROM ArchiveDB.dbo.YourTable DST
WHERE SRC.[ID] = DST.[ID] )
-- Delete from ProdDB if older than 30 days and has been moved to the ArchiveDB
DELETE FROM ProdDB.dbo.YourTable
WHERE DateRecord < DATEADD(d, -30, GETDATE())
AND EXISTS (
SELECT 1 FROM ArchiveDB.dbo.YourTable DST
WHERE [ID] = DST.[ID] )
答案 1 :(得分:0)
我正在查阅@Angel M.的代码,并且我得到了运行的结果。谢谢天使
BEGIN
DECLARE @Ngayhientai Datetime = GETDATE();
DECLARE @ngayquakhu Datetime;
DECLARE @datrungay Datetime;
DECLARE @Daylakieuso int;
DECLARE @lastyear int;
SELECT TOP(1) @ngayquakhu = daylabientable.DateTime
FROM [DatabaseMobus].[dbo].TableModbus daylabientable;
SELECT @Daylakieuso = DATEDIFF(d,@ngayquakhu,@Ngayhientai)
FROM [DatabaseMobus].[dbo].[TableModbus];
IF @Daylakieuso>1
INSERT INTO [DatabaseMobus].[dbo].[SaoluuTable]([STT],[RegisterModbus],[DateTime])
SELECT [STT],[RegisterModbus],[DateTime]
FROM [DatabaseMobus].[dbo].[TableModbus] nguondulieu
WHERE NOT EXISTS(SELECT 1 FROM [DatabaseMobus].[dbo].[SaoluuTable] laylinkgoc
WHERE laylinkgoc.DateTime = nguondulieu.DateTime);
SELECT TOP(1) @datrungay = honmotthang.DateTime
FROM [DatabaseMobus].[dbo].[SaoluuTable] honmotthang;
SELECT @lastyear = DATEDIFF(d,@datrungay,@Ngayhientai)
FROM [DatabaseMobus].[dbo].[TableModbus];
IF @lastyear=365
INSERT INTO [DatabaseMobus].[dbo].[Dulieuhon1nam]([STT],[RegisterModbus],[DateTime])
SELECT [STT],[RegisterModbus],[DateTime]
FROM [DatabaseMobus].[dbo].[SaoluuTable] thoidinhe
WHERE NOT EXISTS(SELECT 1 FROM [DatabaseMobus].[dbo].[SaoluuTable] chisokhac
WHERE chisokhac.DateTime = thoidinhe.DateTime);
IF @lastyear>365
DELETE FROM [DatabaseMobus].[dbo].[SaoluuTable];
END