清除数据库中大于10W行的垃圾历史数据

-- =============================================
-- Author: <Author,Name,龙鸿轩>
-- Create date: <Create Date,2016-01-30>
-- Description: <Description,清除数据库中大于10W行的垃圾历史数据>
-- =============================================
IF object_id('tempdb..#temp') is not null
DROP TABLE #temp
CREATE TABLE #temp (TableName VARCHAR (255), RowCnt INT)
EXEC sp_MSforeachtable 'INSERT INTO #temp SELECT ''?'', COUNT(*) FROM ? having COUNT(*)>100000'
SELECT TableName, RowCnt FROM #temp ORDER BY RowCnt desc

DECLARE @s nvarchar(1000)
DECLARE @table nvarchar(50)
DECLARE Basura_Cursor CURSOR FOR
SELECT replace(replace(TableName,'[dbo].[','' ) ,']','') FROM #temp
OPEN Basura_Cursor;
FETCH NEXT FROM Basura_Cursor into @table;

SET @s ='truncate table ' +@table +' '
EXECUTE(@s)

WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM Basura_Cursor into @table;
set @s ='truncate table ' +@table +' '
EXECUTE(@s)
END;
CLOSE Basura_Cursor;
DEALLOCATE Basura_Cursor;
GO

posted @ 2016-01-30 14:52  龙鸿轩  阅读(302)  评论(0编辑  收藏  举报