
September 27, 2011 15:34 by
this will loop thru all tables that have a frag% > 40 and also puts the schema in front of the table name.
create table #frag(
tabName varchar(200)
)
insert into #frag
select S.name + ‘.’ + tbl.[name] TableName
from sys.dm_db_index_physical_stats (null, null, null, null, null )as mn
inner join sys.tables tbl on tbl.[object_id] = mn.[object_id]
inner join sys.indexes ind on ind.[object_id] = mn.[object_id]
inner join sys.schemas S on tbl.schema_id = S.schema_id
where [database_id] = db_id() and mn.avg_fragmentation_in_percent > 40
order by mn.avg_fragmentation_in_percent desc
while exists(select top 1 tabName from #frag)
begin
declare @name as varchar(200), @sql varchar(1000)
select top 1 @name = tabName from #frag
set @sql = ‘ALTER INDEX ALL ON ‘ + @name + ‘ REBUILD’
select @sql
delete from #frag where tabName = @name
exec(@sql)
end
drop table #frag
8c70a261-7d21-4a73-a01f-e27f0aafedd2|0|.0