Skip to content

Instantly share code, notes, and snippets.

@Laicure
Last active February 16, 2017 23:15
Show Gist options
  • Save Laicure/6415e295e87b984ab03e059b5e61b706 to your computer and use it in GitHub Desktop.
Save Laicure/6415e295e87b984ab03e059b5e61b706 to your computer and use it in GitHub Desktop.
Auto Rebuild/ReOrganize by Fragmentation Size thing :/
set nocount on
--Values to Tempo
SELECT
ind.index_id as 'IDx',
OBJECT_NAME(ind.OBJECT_ID) AS [Table],
ind.name AS [Index],
indexstats.index_type_desc AS [Type],
indexstats.avg_fragmentation_in_percent as [Frag]
into #Tempoo
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
INNER JOIN sys.indexes ind ON ind.object_id = indexstats.object_id AND ind.index_id = indexstats.index_id
WHERE indexstats.index_type_desc<>'HEAP'
--Check Previous Frags
SELECT
ind.index_id as 'IDx',
OBJECT_NAME(ind.OBJECT_ID) AS [Table],
ind.name AS [Index],
indexstats.index_type_desc AS [Type],
indexstats.avg_fragmentation_in_percent as [Frag]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
INNER JOIN sys.indexes ind ON ind.object_id = indexstats.object_id AND ind.index_id = indexstats.index_id
WHERE indexstats.index_type_desc<>'HEAP'
ORDER BY ind.name, indexstats.avg_fragmentation_in_percent DESC
--Cursor Loop to Exec
declare @Que nvarchar(max)
declare QueCur Cursor for (select distinct [Exec] from (select case
when [Frag]>=20 and [Frag]<60 then 'ALTER INDEX [' + [Index] + '] on [' + [Table] + '] ReOrganize'
when [Frag]>=60 then 'ALTER INDEX [' + [Index] + '] on [' + [Table] + '] ReBuild'
else null End as 'Exec'
from #tempoo where [Index] is not null and [Table] is not null)
xx where [Exec] is not null)
open QueCur
Fetch Next from QueCur into @Que
WHILE @@FETCH_STATUS = 0
BEGIN
--exec sp_executeSQL @Que
exec sp_executeSQL @Que
Fetch Next from QueCur into @Que
End
close QueCur
deallocate QueCur
--Check Previous Frags
SELECT
ind.index_id as 'IDx',
OBJECT_NAME(ind.OBJECT_ID) AS [Table],
ind.name AS [Index],
indexstats.index_type_desc AS [Type],
indexstats.avg_fragmentation_in_percent as [Frag]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
INNER JOIN sys.indexes ind ON ind.object_id = indexstats.object_id AND ind.index_id = indexstats.index_id
WHERE indexstats.index_type_desc<>'HEAP'
ORDER BY ind.name, indexstats.avg_fragmentation_in_percent DESC
drop table #Tempoo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment