Truncating SQL Server Log files to free space occupied by SQL Server using DBCC SHRINKFILE Command. Resolving Error:9002 in SQL Server

Introduction: Log Files are usually stored by SQL server whenever there are transaction, whenever we are executing transactions in a sql query the log files size grows up.
The information stored in the log files will be as it is and will not be deleted once the transactions are complete causing the file size of the log files to grow up
Hence we have to periodically truncate the log files so that space is freed for proper working of the database
This is a perfect remedy when we get errors like -
Error: 9002, Severity: 17, State: 2
The log file for database '%.*ls' is full.

Following is the syntax of the set of commands to free up space
Syntax:
-- Truncate the log by changing the database recovery model to SIMPLE
ALTER DATABASE <Database_Name> SET RECOVERY SIMPLE
GO

-- Shrink the truncated log file to the required target sizeDBCC SHRINKFILE(<Database_LogFile_Name>,<Target_size>)
GO

-- Reset the database recovery modelALTER DATABASE <Database_Name> SET RECOVERY FULL
GO


Here,
Database_Name is the Logical Name of the Database for the which the log files needs to be shrunk
Database_LogFile_Name is the Logical Name of Log file to be shrunk.
Target_Size is the file size of the Log files (in MB)
Use below query to find the Name the database and the Log files of the database
SELECT NAME, PHYSICAL_NAME AS current_file_location FROM sys.master_files

Example:
Database Name is TestDatabase
Log file Name for TestDatabase is TestDatabase_log
ALTER DATABASE TestDatabase SET RECOVERY SIMPLE
GO

DBCC SHRINKFILE(TestDatabase_log,1)
GO

ALTER DATABASE TestDatabase SET RECOVERY FULL
GO


Further Reading

How to consolidate physical files and rename the logical file name in SQL Server 2000 and in SQL Server 2005
http://support.microsoft.com/kb/814576/en-us

Manage the Size of the Transaction Log File
https://msdn.microsoft.com/en-us/library/ms365418.aspx

Truncating the Transaction Log
https://technet.microsoft.com/en-us/library/aa174538%28v=sql.80%29.aspx

No comments: