Jac*_*tti 2 sql sql-server archive sql-server-2008
在午夜,我通过在存储过程中执行此操作来存档SQL Server 2008表:
INSERT INTO archive(col1, col2....)
select col1, col2...
from tablename
where date <= @endDate
delete from tablename where date <= @enddate
Run Code Online (Sandbox Code Playgroud)
这是表模式.我明显改变了列名.归档表是完全相同的结构.
[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,
Run Code Online (Sandbox Code Playgroud)
该表通常有大约100,000 - 150,0000行具有多个索引,并且在我尝试执行此归档时仍然会向其写入信息.
这个过程需要最快,6分钟,最慢,13分钟.
有更快的方法吗?
分区是最快的技术,但增加了复杂性并需要Enterprise Edition.
另一种方法是使用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;
Run Code Online (Sandbox Code Playgroud)
如果由于并发插入而遇到阻塞问题,那么可以通过循环批处理上述语句:
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
Run Code Online (Sandbox Code Playgroud)
附加说明:输出表有一些限制.它不能有触发器,涉及外键或具有检查约束.