Sql-server – How to automatically shrink a SQL Server transaction log only if it exceeds a certain limit (e.g. 20 GB)

backupsql servertransaction-log

Our database is set to FULL recovery mode and we take a database backup and a log backup every night. On several occasions we have noticed that the transaction log file is not truncated after the log backup. The log_reuse_wait_desc shows LOG_BACKUP. So we have to run couple of iterations for log backup and sometimes even dbcc shrinkfile command.

Is there any way we can run the dbcc shrinkfile command to shrink the log file every time it reaches 20 GB?

The predefined 'Shrink' maintenance plan is only for the .mdf file which I don't want to do. I believe we'll have to do it through t-sql only and use a trigger but I am unable to make it work. We have a relatively small database and we are running SQL 2012 standard edition. Any pointers you can provide would be immensely helpful.

Best Answer

Our database is set to FULL recovery mode and we take a database backup and a log backup every night.

I think you need to take log backups much more often than every night. Try every hour to see if that keeps your file growth in check. If not you may need to run them more frequently.

You could also deploy an SQL Agent Alert that triggers when the log percent used reaches a certain threshold. This alert could send an email or fire an agent job that runs a log backup job.

Also I wouldn't ever recommend automatically shrinking files.