Shrink and manage huge SQL log file
I had a bad experience with transaction log file, it was 8 years ago. But thanks to Mr.Bad, I learnt very important lesson as newbie DBA at that time. This is the story: my ERP application which sitting on top of SQL Server 2000 was fine at Friday afternoon. I went home for a weekend, only to find everybody was starred at me at Monday morning. What had happened? The ERP was crashed, actually it couldn’t start at all.
I went to my SQL Server box, and the guy was stopped. It’s not started. I checked everything from security permission to possibility of virus, nil. Then I found that the disk was out of space because of transaction log explosion. The accounting guy was doing quarterly stock journal in the system, and it caused transaction log growth exponentially. There was an audit table which recording all journal operation, and obviously the INSERT operation was the source of problem.
Moral of the story: make sure you have automated way to manage transaction log growth.
There are 2 way to shrink the log:
- Detach database, delete the big log, and re-attach without log file. SQL Server will create a new, fresh log file with minimum initial size. It is 2MB by default. Disadvantage: the database will not be available during the process. Offline duration depends on how fast is the detach – attach operation takes time.
- Better approach: use SHRINKFILE of DBCC command. This is better because I do not need to bring the system OFF.
Regardless of the approach, make sure to do full database backup. Shrinking the log deletes historical transaction that may be needed to restore database to specific point of time. Just in case, make sure to do full backup. You have been warned right
.
These are the steps to shrink a huge log file:
First, obtain the log filename, simply use sp_helpdb as follow:
sp_helpdb 'AdventureWorks'
It returns all files in AdventureWorks:
Then shrink AdventureWorks log file to 2 MB size:
USE AdventureWorks
GO
DBCC SHRINKFILE (AdventureWorks_Log, 2)
GO
The outcome is 20 GB log file has been shrunken to 2 MB:
I usually run DBCC SHRINKFILE on scheduled basis, by attaching SQL script to SQL Agent job. This is easier and painless
.