-- Loop through all the tables in the database. FETCH NEXT FROM tables INTO @tablename;
WHILE @@FETCH_STATUS = 0 BEGIN; -- Do the showcontig of all indexes of the table INSERT INTO #fraglist EXEC ("DBCC SHOWCONTIG (""" + @tablename + """) WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS"); FETCH NEXT FROM tables INTO @tablename; END;
-- Close and deallocate the cursor. CLOSE tables; DEALLOCATE tables;
-- Declare the cursor for the list of indexes to be defragged. DECLARE indexes CURSOR FOR SELECT ObjectName, ObjectId,IndexName,IndexId, LogicalFrag FROM #fraglist WHERE INDEXPROPERTY (ObjectId, IndexName, "IndexDepth") > 0;
-- Open the cursor. OPEN indexes;
-- Loop through the indexes. FETCH NEXT FROM indexes INTO @tablename, @objectid, @IndexName,@indexid, @frag;
WHILE @@FETCH_STATUS = 0 BEGIN; if @frag < @maxfrag Begin SELECT @execstr = "ALTER INDEX [" + RTRIM(@IndexName) + "] ON [" + RTRIM(@tablename) + "] REORGANIZE WITH ( LOB_COMPACTION = ON ) " print @maxfrag + " " + @execstr End else Begin SELECT @execstr = "ALTER INDEX [" + RTRIM(@IndexName) + "] ON [" + RTRIM(@tablename) + "] REBUILD WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, SORT_IN_TEMPDB = OFF, ONLINE = OFF )" print @maxfrag + " " + @execstr End
EXEC (@execstr);
--更新统计信息 IF @TmpName<>@tablename BEGIN SET @tmpName=@tableName PRINT "UPDATE STATISTICS "+@TableName + " WITH FULLSCAN " EXEC ("UPDATE STATISTICS "+@TableName + " WITH FULLSCAN ") END
FETCH NEXT FROM indexes INTO @tablename, @objectid, @IndexName,@indexid, @frag; END;
-- Close and deallocate the cursor. CLOSE indexes; DEALLOCATE indexes;
-- Delete the temporary table. DROP TABLE #fraglist; GO