Last active
October 19, 2022 14:44
-
-
Save OsirisDBA/d1846da67297bdf68d798e794f38932b to your computer and use it in GitHub Desktop.
This gives the command to compress SQL Server tables if they aren't already compressed. For SQL Express, remove the ONLINE=ON option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT --TOP 100 | |
s.name + '.' + t.Name AS [Table Name], | |
part.rows AS [Total Rows In Table - Modified], | |
CAST((SUM( DISTINCT au.Total_pages) * 8 ) / 1024.000 / 1024.000 AS NUMERIC(18, 3)) | |
AS [Table's Total Space In GB], | |
'ALTER TABLE [' + s.name + '].[' + t.Name + '] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE, ONLINE=ON);' AS [daSQL] | |
FROM | |
SYS.Tables t INNER JOIN sys.schemas s ON t.schema_id = s.schema_id | |
INNER JOIN SYS.Indexes idx ON t.Object_id = idx.Object_id | |
INNER JOIN SYS.Partitions part ON idx.Object_id = part.Object_id | |
AND idx.Index_id = part.Index_id | |
INNER JOIN SYS.Allocation_units au ON part.Partition_id = au.Container_id | |
INNER JOIN SYS.Filegroups fGrp ON idx.Data_space_id = fGrp.Data_space_id | |
INNER JOIN SYS.Database_files Df ON Df.Data_space_id = fGrp.Data_space_id | |
WHERE t.Is_ms_shipped = 0 AND idx.Object_id > 255 | |
AND part.data_compression = 0 | |
GROUP BY t.Name, s.name, part.rows | |
ORDER BY [Table's Total Space In GB] DESC; | |
--SELECT 1; | |
SELECT | |
'ALTER INDEX [' + i.name + '] ON [' + OBJECT_SCHEMA_NAME(s.Object_id) + '].[' + OBJECT_NAME(s.object_ID) + '] REBUILD PARTITION = ALL WITH ( ONLINE = ON, DATA_COMPRESSION = PAGE);' AS daSQL, | |
OBJECT_SCHEMA_NAME(s.Object_id) AS SchemaName, | |
OBJECT_NAME(s.object_ID) AS TableName, | |
i.name AS IndexName, | |
SUM(s.used_page_count) * 8 / 1024 AS IndexSizeMB | |
FROM sys.dm_db_partition_stats AS s | |
JOIN sys.indexes AS i | |
ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id | |
join sys.partitions p on p.object_id = s.Object_id and p.index_id = s.index_id | |
WHERE i.index_id <> 1 | |
AND p.data_compression = 0 | |
AND i.name IS NOT NULL | |
AND Object_Schema_Name(s.Object_id) <> 'sys' | |
GROUP BY Object_Schema_Name(s.Object_id), | |
Object_Name(s.object_ID) , | |
i.name | |
ORDER BY IndexSizeMB DESC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment