declare@xint set@x=1000 while@x<10000 begin insertinto t3 values (@x,'qweasdqweasdqweasdqweqweasdqwe') set@x=@x+1 end
再执行语句:
SELECT index_id,index_type_desc,avg_fragmentation_in_percent,page_count FROM sys.dm_db_index_physical_stats(db_id(), OBJECT_ID('t3'), NULL, NULL , 'LIMITED'); alterindex t3index on t3 rebuild
-- ensure a USE <databasename> statement has been executed first. SET NOCOUNT ON; DECLARE@objectidint; DECLARE@indexidint; DECLARE@partitioncountbigint; DECLARE@schemaname sysname; DECLARE@objectname sysname; DECLARE@indexname sysname; DECLARE@partitionnumbigint; DECLARE@partitionsbigint; DECLARE@fragfloat; DECLARE@commandvarchar(8000); -- ensure the temporary table does not exist IFEXISTS (SELECT name FROM sys.objects WHERE name ='work_to_do') DROPTABLE work_to_do; -- conditionally select from the function, converting object and index IDs to names. SELECT object_idAS objectid, index_id AS indexid, partition_number AS partitionnum, avg_fragmentation_in_percent AS frag INTO work_to_do FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') WHERE avg_fragmentation_in_percent >10.0AND index_id >0; -- Declare the cursor for the list of partitions to be processed. DECLARE partitions CURSORFORSELECT*FROM work_to_do; -- Open the cursor. OPEN partitions; -- Loop through the partitions. FETCHNEXT FROM partitions INTO@objectid, @indexid, @partitionnum, @frag; WHILE@@FETCH_STATUS=0 BEGIN; SELECT@objectname= o.name, @schemaname= s.name FROM sys.objects AS o JOIN sys.schemas as s ON s.schema_id = o.schema_id WHERE o.object_id=@objectid; SELECT@indexname= name FROM sys.indexes WHEREobject_id=@objectidAND index_id =@indexid; SELECT@partitioncount=count (*) FROM sys.partitions WHEREobject_id=@objectidAND index_id =@indexid; -- 30 is an arbitrary decision point at which to switch between reorganizing and rebuilding IF@frag<30.0 BEGIN; SELECT@command='ALTER INDEX '+@indexname+' ON '+@schemaname+'.'+@objectname+' REORGANIZE'; IF@partitioncount>1 SELECT@command=@command+' PARTITION='+CONVERT (CHAR, @partitionnum); EXEC (@command); END; IF@frag>=30.0 BEGIN; SELECT@command='ALTER INDEX '+@indexname+' ON '+@schemaname+'.'+@objectname+' REBUILD'; IF@partitioncount>1 SELECT@command=@command+' PARTITION='+CONVERT (CHAR, @partitionnum); EXEC (@command); END; PRINT'Executed '+@command; FETCHNEXTFROM partitions INTO@objectid, @indexid, @partitionnum, @frag; END; -- Close and deallocate the cursor. CLOSE partitions; DEALLOCATE partitions; -- drop the temporary table IFEXISTS (SELECT name FROM sys.objects WHERE name ='work_to_do') DROPTABLE work_to_do; GO