Question

How do I truncate the transaction log in a SQL Server 2008 database?

What are possible best ways?

I tried this from a blog as follows:

1) From the setting database to simple recovery, shrinking the file and once again setting in full recovery, you are in fact losing your valuable log data and will be not able to restore point in time. Not only that, you will also not be able to use subsequent log files.

2) Shrinking database file or database adds fragmentation.

There are a lot of things you can do. First, start taking proper log backup using the following command instead of truncating them and losing them frequently.

BACKUP LOG [TestDb] TO  DISK = N'C:\Backup\TestDb.bak'
GO

Remove the code of SHRINKING the file. If you are taking proper log backups, your log file usually (again usually, special cases are excluded) do not grow very big.

Was it helpful?

Solution

The safest and correct way to truncate a log file if the database is in Full Recovery Mode is to do a Transaction Log Backup (without TRUNCATE_ONLY. This is going to be deprecated in future releases and is not advisable).

It sounds like you want to shrink your log file afterwards, in which case you'd run a DBCC SHRINKFILE(yourTLogName) command. There is an optional second parameter for the requested size to shrink it to.

OTHER TIPS

You could backup the log to the null device:

backup log [databasename] to disk = 'nul';

Or you could switch the recovery model to simple and then back to full/bulk again.

If you do not care about your log data and just want to get rid of it:

Change the recovery model from full to simple, and then back to full. Shrink the file using DBCC SHRINKFILE with the TRUNCATEONLY argument

The following command will change the recovery model from full to simple

ALTER DATABASE <databse_name> SET RECOVERY SIMPLE

The following command will change the recovery model to full

ALTER DATABASE <databse_name> SET RECOVERY FULL

To find the name of the log file you can use the following query

SELECT name 
FROM sys.master_files
WHERE database_id = DB_ID('<databse_name>')

Shrink the file

DBCC SHRINKFILE (N'<logical_file_name_of_the_log>' , 0, TRUNCATEONLY)

See What is the command to truncate a SQL Server log file? for more information on this

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top