Thursday, 14 November 2024

to shrink all databases on your server

DECLARE @DB_Name NVARCHAR(255);

DECLARE @DB_LgoFileName NVARCHAR(255);

DECLARE @ScriptsList NVARCHAR(max);


DECLARE db_cursor CURSOR FOR

SELECT name

FROM sys.databases

WHERE  state_desc = 'ONLINE' and name NOT IN ('master', 'model', 'msdb', 'tempdb'); -- Exclude system databases


OPEN db_cursor;

FETCH NEXT FROM db_cursor INTO @DB_Name;


WHILE @@FETCH_STATUS = 0

BEGIN

    SET @DB_LgoFileName = (SELECT name FROM sys.master_files WHERE type_desc = 'LOG' AND database_id = DB_ID(@DB_Name));

set @DB_LgoFileName='['+@DB_LgoFileName+']';

set @DB_Name='['+@DB_Name+']';

print '@DB_Name: '+ @DB_Name;

print '@DB_LgoFileName: '+ @DB_LgoFileName;


set @ScriptsList= 'USE ' + @DB_Name + ';';


    -- Shrink the log file

    set @ScriptsList=@ScriptsList+' ' +('DBCC SHRINKFILE (' + @DB_LgoFileName + ', 1);');


    -- Shrink the database

    set @ScriptsList=@ScriptsList+' '+('DBCC SHRINKDATABASE (' + @DB_Name + ');');


    -- Set recovery model to SIMPLE

    set @ScriptsList=@ScriptsList+' '+('ALTER DATABASE ' + @DB_Name + ' SET RECOVERY SIMPLE;');


    -- Shrink the log file again

    set @ScriptsList=@ScriptsList+' '+('DBCC SHRINKFILE (' + @DB_LgoFileName + ', 1);');


    -- Set recovery model back to FULL

    set @ScriptsList=@ScriptsList+' '+('ALTER DATABASE ' + @DB_Name + ' SET RECOVERY FULL;');

EXEC(@ScriptsList);

    FETCH NEXT FROM db_cursor INTO @DB_Name;

END


CLOSE db_cursor;

DEALLOCATE db_cursor;