Lista tabel wraz z ilością wierszy i zajmowaną przestrzenią
SELECT
s.Name [SchemaName],
t.Name [TableName],
p.rows [RowCounts],
CAST(ROUND((SUM(a.used_pages) / 128.00), 2) AS NUMERIC(36, 2)) [Used MB],
CAST(ROUND((SUM(a.total_pages) - SUM(a.used_pages)) / 128.00, 2) AS NUMERIC(36, 2)) [Unused MB],
CAST(ROUND((SUM(a.total_pages) / 128.00), 2) AS NUMERIC(36, 2)) [Total MB]
FROM sys.tables t
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE i.type IN (0,1) --0 = Heap, 1 = Clustered rowstore (B-tree)
GROUP BY t.Name, s.Name, p.Rows
ORDER BY p.Rows DESC, s.Name, t.Name;
Lista zdefragmentowanych indeksów wraz z poleceniem przebudowy
SELECT s.name [Schema],
t.name [Table],
i.name [Index],
ips.avg_fragmentation_in_percent,
ips.page_count,
CONCAT('ALTER INDEX ', i.name, ' ON ', t.name,' REBUILD;') [Rebuild cmd]
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) ips
INNER JOIN sys.tables t ON t.object_id = ips.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN sys.indexes i ON i.object_id = ips.object_id
AND ips.index_id = i.index_id
WHERE ips.database_id = DB_ID()
AND i.name IS NOT NULL
AND ips.avg_fragmentation_in_percent > 30
ORDER BY ips.avg_fragmentation_in_percent DESC;