Occasionally the log file on a database will grow to an alarming size, or disk space will be short, and you find that running DBCC SHRINKFILE and BACKUP LOG do not reduce the log file’s size.
Run: DBCC LOGINFO (database name) and check the last entry; if the last entry’s status is 2, then the end of the transaction log is the active portion. This can have the effect of preventing the log file’s reduction. To reduce the log file we need to somehow force the active part of the log back to the beginning, thus setting the end of the transaction log as being unused.
To reduce the file, follow these steps:
Step 1
- run: DBCC SHRINKFILE (logfile, TRUNCATEONLY )
- run: BACKUP LOG database WITH TRUNCATE_ONLY
Step 2
- Create a dummy table and insert a record to MyTable
- CREATE TABLE MyTable (MyField VARCHAR(10), PK INT )
- INSERT Mytable (PK) VALUES (1)
- GO
Step 3
Create and run the following script:
SET NOCOUNT ON
DECLARE @Index INT
SELECT @Index = 0
WHILE (@Index < 20000)
BEGIN
UPDATE MyTable SET MyField = MyField WHERE PK = 1
SELECT @Index = @Index + 1
END
SET NOCOUNT OFF
If this is run successfully, the log rows with a status of 2 will wrap around to the beginning (or some other unused part) of the log file. The later parts of the log file will become marked as unused, and the next DBCC SHRINKFILE and BACKUP LOG will truncate the log:
Step 4
Run these commands again:
- DBCC SHRINKFILE (logfile, truncateonly )
- BACKUP LOG database name WITH TRUNCATE_ONLY
The log file should now be smaller.