Skip to main content

A handy SQL Server script to shrink all database files.

-- article: http://www.technologytoolbox.com/blog/jjameson/archive/2008/05/30/shrinking-all-database-files.aspx
-- github: https://github.com/jeremy-jameson/Toolbox/blob/master/SQL/Shrink%20All%20Database%20Files.sql

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

insert into @commandQueue(SqlStatement)
    select 'USE [' + A.name + '] DBCC SHRINKFILE (N''' + B.name + ''' , 1)'
    from sys.databases as A
    inner join sys.master_files as B
        on A.database_id = B.database_id
    where A.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;