清除数据库中大于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

原文地址:https://www.cnblogs.com/ignacio/p/5171065.html