Q&A: Script for the Job that will shrink the log files for all databases

There was a user question on how to shrink the log files with dynamic SQL (without hard coding databases names). The script is provided below. But first – make sure that you size the log files properly (large enough to grow) and make sure that you backup regularly the log files (or use simple recovery mode). And do not truncate the logs, shrink them just to the size you need. So, if my log files do not usually grow larger than 4 GB I will use the following script:

SET NOCOUNT ON
CREATE table #tran_log_space_usage(
database_name sysname
, log_size_mb float
, log_space_used float
, status int
);
insert into #tran_log_space_usage
exec(‘DBCC SQLPERF ( LOGSPACE )’) ;

delete from #tran_log_space_usage where database_name = ‘Exclude_DB’

EXEC dbo.sp_msforeachdb ‘
DECLARE @log_file VARCHAR(150)
IF (SELECT DB_ID(”?”)) > 4 and (SELECT DATABASEPROPERTY(”?”, ”IsOffline”)) <>1
BEGIN
PRINT ”?”
IF (select log_size_mb as LogSizeMB
from #tran_log_space_usage
where database_name = ”?”) > 4048
BEGIN
select @log_file = name
from [?].sys.database_files where file_id = 2
USE [?]
DBCC SHRINKFILE (@log_file , 4048)
END
PRINT ”/*********************************/”
END’

DROP table #tran_log_space_usage

You can add exceptions for the databases as well (see ‘Exclude_DB’ in script).