Скрипт сжатие таблиц mssqlserver

DECLARE @Table_catalog NVARCHAR(128)
DECLARE @Table_schema NVARCHAR(128)
DECLARE @Table_name NVARCHAR(128)
DECLARE @Index_Name NVARCHAR(128)

DECLARE @cmd VARCHAR(4000)

— включение сжатия для таблиц
DECLARE TableNameCursor CURSOR
FOR
SELECT Table_catalog, Table_schema, Table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ‘BASE TABLE’
ORDER BY Table_catalog, Table_schema, Table_name

OPEN TableNameCursor

FETCH NEXT FROM TableNameCursor INTO @Table_catalog, @Table_schema, @Table_name
WHILE @@fetch_status = 0
BEGIN

PRINT @Table_catalog + ‘.’ + @Table_schema + ‘.’ + @Table_name
SET @cmd = ‘ALTER TABLE [‘ + @Table_catalog + ‘].[‘ + @Table_schema + ‘].[‘ + @Table_name + ‘] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)’
EXEC (@cmd)

FETCH NEXT FROM TableNameCursor INTO @Table_catalog, @Table_schema, @Table_name
END
CLOSE TableNameCursor
DEALLOCATE TableNameCursor

— включение сжатия для индексов
DECLARE IndexCursor CURSOR
FOR
SELECT DB_NAME(), schemas.name, tables.name, indexes.name
FROM sys.schemas as schemas inner join sys.tables as tables inner join sys.indexes as indexes on tables.object_id = indexes.object_id on schemas.schema_id = tables.schema_id
ORDER BY schemas.name, tables.name, indexes.name;

OPEN IndexCursor

FETCH NEXT FROM IndexCursor INTO @Table_catalog, @Table_schema, @Table_name, @Index_Name
WHILE @@fetch_status = 0
BEGIN

PRINT @Table_catalog + ‘.’ + @Table_schema + ‘.’ + @Table_name + ‘: ‘ + @Index_Name

SET @cmd = ‘ALTER INDEX [‘ + @Index_Name + ‘] ON [‘ + @Table_catalog + ‘].[‘ + @Table_schema + ‘].[‘ + @Table_name + ‘] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)’
EXEC (@cmd)

FETCH NEXT FROM IndexCursor INTO @Table_catalog, @Table_schema, @Table_name, @Index_Name
END
CLOSE IndexCursor
DEALLOCATE IndexCursor

— делаем шринк базы — возвращаем свободное место на диск
SELECT @cmd=(
SELECT ‘DBCC SHRINKDATABASE(»’+ DB_NAME() + »’)’
)
EXEC (@cmd)

Нагрузка на файлы

SELECT d.name, f.name, f.type_desc, f.physical_name,
[read b/ms] = num_of_bytes_read * 1.0/sample_ms,
[avg read latency] =
(1.0*s.io_stall_read_ms / (COALESCE(NULLIF(s.num_of_reads,0),1))),
[write b/ms] = num_of_bytes_written * 1.0/sample_ms,
[avg write latency] =
(1.0*s.io_stall_write_ms / (COALESCE(NULLIF(s.num_of_writes,0),1)))
FROM sys.master_files AS f
INNER JOIN sys.databases AS d
ON f.database_id = d.database_id
INNER JOIN sys.dm_io_virtual_file_stats(default, default) AS s
ON d.database_id = s.database_id
AND f.[file_id] = s.[file_id]
order by 8 desc