;
WITH GetFragmatation AS
( SELECT object_id AS ObjectID ,
OBJECT_NAME(object_id) AS TableName ,
index_id AS IndexID ,
avg_fragmentation_in_percent AS PercentFragment,
fragment_count AS TotalFrags ,
avg_fragment_size_in_pages AS PagesPerFrag ,
page_count AS NumPages
FROM sys.dm_db_index_physical_stats(DB_ID('RKPMS'), NULL, NULL, NULL , 'DETAILED')
WHERE avg_fragmentation_in_percent > 0
)
SELECT gf.ObjectID ,
'['+SCHEMA_NAME(schema_id)+'].['+Sch.name+']' AS FullName,
gf.TableName ,
gf.IndexID ,
IND.name AS IndexName ,
gf.PercentFragment ,
gf.TotalFrags ,
gf.PagesPerFrag ,
gf.NumPages
FROM GetFragmatation AS gf
INNER JOIN sys.indexes AS ind
ON ind.object_id = gf.ObjectID
AND index_id = gf.IndexID
INNER JOIN sys.tables AS Sch
ON Sch.object_id = gf.ObjectID
--Use the below one to defragment the Index
ALTER INDEX PK_TableNameIndexName
ON [dbo].[TableName]REBUILD WITH ( FILLFACTOR = 70, ONLINE = ON )
--To alter all the index for a table
--ALTER INDEX ALL ON TableName REBUILD
SELECT object_name(IPS.object_id) AS [TableName],
SI.name AS [IndexName],
IPS.Index_type_desc,
IPS.avg_fragmentation_in_percent AS [Percentage of the logical index that is fragmented],
IPS.avg_fragment_size_in_pages AS [Average number of pages in a leaf-level fragment.],
IPS.avg_page_space_used_in_percent,
IPS.record_count AS [Total number of records],
IPS.ghost_record_count,
IPS.fragment_count AS [Number of fragments in the leaf level.],
IPS.avg_fragment_size_in_pages AS PagesPerFrag,
IPS.page_count AS [Number of index or data pages.]
FROM sys.dm_db_index_physical_stats(db_id(N'Rkpms'), NULL, NULL, NULL , 'DETAILED') IPS
JOIN sys.tables ST WITH (nolock) ON IPS.object_id = ST.object_id
JOIN sys.indexes SI WITH (nolock) ON IPS.object_id = SI.object_id AND IPS.index_id = SI.index_id
WHERE ST.is_ms_shipped = 0 AND ST.TYPE = 'U'
ORDER BY 4 DESC
No comments:
Post a Comment