Skip to main content

A very helpful SQL Server script to periodically free up disk space in shared development environments (DEV), and especially local VMs.

-- article: http://www.technologytoolbox.com/blog/jjameson/archive/2008/05/30/truncating-all-transaction-logs.aspx
-- github: https://github.com/jeremy-jameson/Toolbox/blob/master/SQL/Truncate%20All%20Transaction%20Logs.sql

declare @commandQueue table (ID int identity(1, 1), SqlStatement varchar(1000) not null);

insert into @commandQueue (SqlStatement)
    select 'BACKUP LOG [' + name + '] WITH TRUNCATE_ONLY'
    from sys.databases
    where name not in ('master', 'model', 'msdb', 'tempdb');

declare @id int;
select @id = min(ID) from @commandQueue;

while @id is not null
    begin
        declare @sqlStatement varchar(1000);
        select @sqlStatement = SqlStatement from @commandQueue where ID = @id;

        print 'Executing ''' + @sqlStatement + '''...';
        exec (@sqlStatement);

        delete from @commandQueue where ID = @id;
        select @id = min(ID) from @commandQueue;
    end;