-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressLargeTables.sql
More file actions
39 lines (31 loc) · 1.04 KB
/
CompressLargeTables.sql
File metadata and controls
39 lines (31 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
-- Compress any table larger than a GB in the DB
DECLARE @SchemaName NVARCHAR(MAX);
DECLARE @TableName NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
-- Loop over each table that is part of the view
DECLARE table_cursor CURSOR FOR
SELECT
s.name AS SchemaName,
o.name AS ObjectName
FROM sys.dm_db_partition_stats AS ps
INNER JOIN sys.objects AS o
ON ps.object_id = o.object_id
INNER JOIN sys.schemas AS s
ON o.schema_id = s.schema_id
GROUP BY s.name, o.name
having SUM(reserved_page_count) * 8.0 / 1024 / 1024 > 1;
OPEN table_cursor;
FETCH NEXT FROM table_cursor INTO @SchemaName, @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
-- Build the dynamic SQL for each table
SET @SQL = 'ALTER TABLE [' + @SchemaName + '].[' + @TableName + '] REBUILD PARTITION = ALL
WITH (DATA_COMPRESSION = PAGE)';
-- Execute the dynamic SQL
EXEC sp_executesql @SQL;
-- Fetch next table name
FETCH NEXT FROM table_cursor INTO @SchemaName, @TableName;
END;
-- Clean up the cursor
CLOSE table_cursor;
DEALLOCATE table_cursor;