---------------------------------------------------------------------------------
---------------- Check Fragmentation in SQL Server ----------------------
---------------------------------------------------------------------------------
-- For Specific Darabase, uncomment the USE USE [Database Name] just below
-- USE [Database Name]
SELECT Db_id() AS DbId,
Object_name(ind.object_id) AS TableName,
ind.name AS IndexName,
indexstats.index_type_desc AS IndexType,
indexstats.avg_fragmentation_in_percent,
indexstats.page_count AS page_count
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.avg_fragmentation_in_percent > 30
--You can specify the percent as you want
ORDER BY indexstats.avg_fragmentation_in_percent DESC;
---------------------------------------------------------------------------------
-- Get Current DatabaseID
-- SELECT DB_ID() DatabaseID;
-- Get Current DatabaseName
-- SELECT DB_NAME() DatabaseName;
-- Get DatabaseName from DatabaseID
-- SELECT DB_NAME(11) DatabaseID;
-- Get DatabaseID from DatabaseName
-- SELECT DB_ID('tempdb') DatabaseName;
-- Get all DatabaseName and DBID
-- SELECT name,database_id FROM sys.databases;
---------------------------------------------------------------------------------