--Ensure a Use <databasename> statement have been executed first. SET NOCOUNT on;declare @objectid int;declare @indexid int;declare @partitioncount bigint;declare @schemaname nvarchar ( 130); DECLARE @objectname nvarchar (130); DECLARE @indexname nvarchar (130); DECLARE @partitionnum bigint;declare @partitions bigint;declare @frag float;declare @command nvarchar (4000); --Conditionally Select tables and indexes from the Sys.dm_db_index_physical_stats function--and convert object and Inde x IDs to names. SELECT object_id as Objectid, index_id as IndexID, partition_number as Partitionnum, AVG_FRAGMENTATION_IN_PERC ent as Fraginto #work_to_doFROM sys.dm_db_index_physical_stats (db_id (), NULL, NULL, NULL, ' LIMITED ') WHERE Avg_fragmenta Tion_in_percent > 10.0 and index_id > 0;--Declare the cursor for the list of partitions to be processed. DECLARE partitions cursor for SELECT * from #work_to_do;--Open the cursor. OPEN partitions;--Loop through the partitions. while (1=1) BEGIN; FETCH NEXT from partitions into @objectid, @indexid, @partitionnum, @frag; IF @ @FETCH_STATUS < 0 break; SELECT @objectname = QUOTENAME (o.name), @schemaname = QUOTENAME (s.name) from sys.objects as O JOIN sys.schem As as s on s.schema_id = o.schema_id WHERE o.object_id = @objectid; SELECT @indexname = QUOTENAME (name) from sys.indexes WHERE object_id = @objectid and index_id = @indexid; SELECT @partitioncount = count (*) from sys.partitions WHERE object_id = @objectid and index_id = @in dexid;--a arbitrary decision point at which to switch between reorganizing and rebuilding. IF @frag < 30.0 SET @command = n ' ALTER INDEX ' + @indexname + n ' on ' + @schemaname + n '. ' + @objectname + N ' REORGANIZE '; IF @frag >= 30.0 SET @command = n ' ALTER INDEX ' + @indexname + n ' on ' + @schemaname + n '. ' + @objectname + N ' REBUILD '; IF @pArtitioncount > 1 SET @command = @command + N ' partition= ' + CAST (@partitionnum as nvarchar (10)); EXEC (@command); PRINT N ' Executed: ' + @command; end;--Close and deallocate the cursor. CLOSE partitions;deallocate partitions;--Drop the temporary table. DROP TABLE #work_to_do; GO
A script job for rebuild DB in AX 2012