[SQL Server] Przydatne skrypty #1
Lista tabel wraz z ilością wierszy i zajmowaną przestrzenią
SELECTs.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 tINNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_idINNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_idINNER JOIN sys.allocation_units a ON p.partition_id = a.container_idINNER JOIN sys.schemas s ON t.schema_id = s.schema_idWHERE i.type IN (0,1) --0 = Heap, 1 = Clustered rowstore (B-tree)GROUP BY t.Name, s.Name, p.RowsORDER 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) ipsINNER JOIN sys.tables t ON t.object_id = ips.object_idINNER JOIN sys.schemas s ON t.schema_id = s.schema_idINNER JOIN sys.indexes i ON i.object_id = ips.object_idAND ips.index_id = i.index_idWHERE ips.database_id = DB_ID()AND i.name IS NOT NULLAND ips.avg_fragmentation_in_percent > 30ORDER BY ips.avg_fragmentation_in_percent DESC;
...