午夜,我通过在存储过程中执行此操作来存档SQL Server 2008表:
INSERT INTO archive(col1, col2....)
select col1, col2...
from tablename
where date <= @endDate
delete from tablename where date <= @enddate
这是表架构。我明显改变了列名。归档表的结构完全相同。
[col1] [uniqueidentifier] NOT NULL,
[col1] [bigint] NOT NULL,
[col1] [nvarchar](255) NOT NULL,
[col1] [nvarchar](255) NOT NULL,
[col1] [datetime] NOT NULL,
[col1] [nvarchar](75) NULL,
[col1] [nvarchar](255) NULL,
[col1] [nvarchar](255) NULL,
[col1] [nvarchar](255) NULL,
[col1] [nvarchar](255) NULL,
[col1] [nvarchar](50) NULL,
[col1] [nvarchar](50) NULL,
[col1] [nvarchar](1000) NULL,
[col1] [nvarchar](2) NULL,
[col1] [nvarchar](255) NULL,
[col1] [nvarchar](255) NULL,
该表通常包含大约100,000 - 150,0000行和多个索引,并且在我尝试执行此归档时仍然会写入信息。
这个过程需要最快,6分钟,最慢,13分钟。
有更快的方法吗?
答案 0 :(得分:6)
分区是最快的技术,但增加了复杂性并需要企业版。
另一种方法是使用OUTPUT子句将DELETE和INSERT合并为一个语句。 http://msdn.microsoft.com/en-us/library/ms177564.aspx。带有OUTPUT子句的DELETE比单个INSERT / DELETE语句更快。
DELETE FROM tablename
OUTPUT DELETED.Col1, DELETED.col2, DELETED.col3 DELETED.col4 -- etc
INTO archive ( col1, col2, col3, col4 )
WHERE date <= @enddate;
如果由于并发插入而导致阻塞问题,那么您可以通过循环批处理上述语句:
DECLARE @i int
SET @i = 1
WHILE @i > 0
BEGIN
DELETE top (1000) FROM tablename
OUTPUT DELETED.Col1, DELETED.col2, DELETED.col3 DELETED.col4 -- Eric
INTO archive ( col1, col2, col3, col4 )
WHERE date <= @enddate
SET @i = @@rowcount
END
附加说明:输出表有一些限制。它不能有触发器,涉及外键或有检查约束。
答案 1 :(得分:1)