--使用 DBCC SHOWCONTIG 和 DBCC DBREINDEX 对数据库中的索引进行碎片整理
-- Declare variables
SET NOCOUNT ON
DECLARE @tablename VARCHAR (128)
DECLARE @execstr VARCHAR (255)
DECLARE @objectid INT
DECLARE @indexid INT
DECLARE @frag DECIMAL
DECLARE @maxfrag DECIMAL
--所能允许的最大碎片程度
SELECT @maxfrag = 10.0
-- 定义所有用户表的游标
DECLARE cur_tables CURSOR FOR
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
-- Create the table
CREATE TABLE #fraglist (
ObjectName CHAR (255),
ObjectId INT,
IndexName CHAR (255),
IndexId INT,
Lvl INT,
CountPages INT,
CountRows INT,
MinRecSize INT,
MaxRecSize INT,
AvgRecSize INT,
ForRecCount INT,
Extents INT,
ExtentSwitches INT,
AvgFreeBytes INT,
AvgPageDensity INT,
ScanDensity DECIMAL,
BestCount INT,
ActualCount INT,
LogicalFrag DECIMAL,
ExtentFrag DECIMAL)
-- Open the cursor
OPEN cur_tables
-- Loop through all the cur_tables in the database
FETCH NEXT
FROM cur_tables
INTO @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
-- Do the showcontig of all cur_indexes of the table
INSERT INTO #fraglist
EXEC ('DBCC SHOWCONTIG (''' + @tablename + ''')
WITH FAST, TABLERESULTS, NO_INFOMSGS')
FETCH NEXT
FROM cur_tables
INTO @tablename
END
-- Close and deallocate the cursor
CLOSE cur_tables
DEALLOCATE cur_tables
-- 定义需要重建索引的表的游标
DECLARE cur_indexes CURSOR FOR
SELECT ObjectName, ObjectId, IndexId, LogicalFrag
FROM #fraglist
WHERE LogicalFrag >= @maxfrag
--AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0
-- Open the cursor
OPEN cur_indexes
-- loop through the cur_indexes
FETCH NEXT
FROM cur_indexes
INTO @tablename, @objectid, @indexid, @frag
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing DBCC DBREINDEX (' + RTRIM(@tablename) + ') - fragmentation currently '
+ RTRIM(CONVERT(varchar(15),@frag)) + '%'
SELECT @execstr = 'DBCC DBREINDEX(' + RTRIM(@tablename) + ')'
EXEC (@execstr)
FETCH NEXT
FROM cur_indexes
INTO @tablename, @objectid, @indexid, @frag
END
-- Close and deallocate the cursor
CLOSE cur_indexes
DEALLOCATE cur_indexes
-- Delete the temporary table
DROP TABLE #fraglist
GO