i am beginner and writing a query to fetch avg fragmentation in percent to rebuild indexex for db i used cursor but i m able to bring for one database so how to include for all database using outer cursor excluding master database … please help me to put outer cursor to bring for all database exlcuding master
my query is like this
DECLARE @TableName VARCHAR(255)
DECLARE @schema VARCHAR(50)
DECLARE @indexName VARCHAR(255)
Declare @avgfrag int
DECLARE @sql NVARCHAR(500)
DECLARE TableCursor CURSOR FOR
SELECT schema_name(t.schema_id) AS [Schema],
object_name(ps.object_id) AS [Table],
i.name AS [Index],
--ps.Index_type_desc AS IndexType,
convert(TINYINT,ps.avg_fragmentation_in_percent) AS [AvgFrag%]
--convert(TINYINT,ps.avg_page_space_used_in_percent) AS [AvgSpaceUsed%],
--ps.record_count AS RecordCnt,
--ps.fragment_count AS FragmentCnt
FROM sys.dm_db_index_physical_stats(db_id(db_name()),NULL,NULL,NULL,'DETAILED') ps -- Faster option: SAMPLED
INNER JOIN sys.indexes i
ON ps.object_id = i.object_id
AND ps.index_id = i.index_id
INNER JOIN sys.tables t
ON ps.object_id = t.object_id
WHERE ps.avg_fragmentation_in_percent >=1
ORDER BY ps.avg_fragmentation_in_percent desc
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @schema,@TableName,@indexname,@avgfrag
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX '+ @indexname + ' ON ' + @Schema +'.'+ @tablename + ' REBUILD ' --+' with (online=on)'
print @SQL +' '+ convert(varchar,@avgfrag)
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @schema,@TableName,@indexname,@avgfrag
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO
Best Answer
This script will loop through all databases and execute the selective reindex script.