Wednesday, May 9, 2018

MS SQL script for compress all database

This script was created for the development server. We have high-speed disks and not enough space, and developers need more databases.
Run this script in MS SQL for compress all database


Declare @DatabaseName as NvarChar(500);
Declare @CURSOR CURSOR;
Declare @SQL nvarchar(max);


SET @CURSOR = CURSOR SCROLL
FOR

SELECT name AS [Database Name]
--,recovery_model_desc AS [Recovery Model]
FROM sys.databases
where name not in ('master', 'tempdb', 'model', 'msdb')
and name not like '%veeam%'
and recovery_model_desc!='SIMPLE'

OPEN @CURSOR

FETCH NEXT FROM @CURSOR INTO @DatabaseName
WHILE @@FETCH_STATUS = 0
BEGIN
print @DatabaseName;
SET @SQL='';
SET @SQL= @SQL+
'USE [master];

ALTER DATABASE ['+@DatabaseName+'] SET RECOVERY SIMPLE WITH NO_WAIT;

use ['+@DatabaseName+'];
EXEC sp_MSforeachtable ''ALTER INDEX ALL ON ? REBUILD WITH (DATA_COMPRESSION = PAGE)'';

EXEC sp_MSforeachtable ''ALTER TABLE ? REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE)'';

USE ['+@DatabaseName+'];

DBCC SHRINKDATABASE(N'''+@DatabaseName+''', 1 );
';
print @SQL
EXEC(@SQL);



FETCH NEXT FROM @CURSOR INTO @DatabaseName
END
CLOSE @CURSOR

GO

No comments:

Post a Comment