Shrink all SQL Server Databases

A quick way to ensure all the databases on your dev pc/server are all set to simple backup and log files are shrunk to avoid wasting disk space.

You can easily add databases to the list you don't want affected.

declare @ssql nvarchar(4000)
set @ssql= '
        if ''?'' not in (''tempdb'',''master'',''model'',''msdb'')
        begin
                  use [?]
                  Alter database [?] SET Recovery simple
        end'

exec sp_msforeachdb @ssql
set @ssql= '
        if ''?'' not in (''tempdb'',''master'',''model'',''msdb'')
        begin    
                  use [?] 
                  Declare @LogFileLogicalName sysname
                  select @LogFileLogicalName=Name from sys.database_files where Type=1
                  --print @LogFileLogicalName

                  DBCC Shrinkfile(@LogFileLogicalName,1)
        end'
exec sp_msforeachdb @ssql

1 comment:

  1. Brilliant !!
    I was doing this manually for the each database that I wanted to shrink.

    Thanks

    ReplyDelete