Technical Article

Backup and Truncate Transaction Logs

,

Our performance and test environment is set on full recovery mode, after every test the database logs where growing outoff control. But not any more.The script will set the database to single user, backup the transaction log ( " optional step") and finaly shrik the log file to 1 mb.

---Find how big is the log
dbcc sqlperf (logspace)
go
use DatabaseNameHere
go
---Find the actual names of the Log Files 
--And Save those names somewhere you will need them.
sp_helpfile
go
--Back to the Master Database
use Master 
go

--- Set database to Single User ( No always necesary )
---And No transactions are pending
Alter Database DatabaseNameHere set single_user with rollback immediate ---If No one on the database
go
--OR
--Set database to single_user once all transactions are done
Alter Database DatabaseNameHere set Single_user with No_wait 
go
---Always is a good idea to backup the transaction log

BACKUP LOG [DatabaseNameHere] TO DISK = N'C:\MSSQL\db_dmp\TLogs\TranLogs.trn'
WITH NOFORMAT, INIT, NAME = N'DatabaseNameHereServices-Transaction Log Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
go
--Now down to bussiness
alter database DatabaseNameHere set recovery Simple; --Set recovery mode to simple
go
use DatabasenameHere --- Point to the right Database
---Use sp_helpfile to get proper log file Name
go
----Copy one per File to keep it simple I only added one

DBCC SHRINKFILE (LOGFILENAMEHERE,1) with no_infomsgs ---1 = 1mb truncate to 1 mb
go

use Master --Set database back to master
go
--Set Database back to full recovery mode
alter database DatabaseNameHere set recovery FULL ;---Set Recovery mode back to Full
go
--Set Database back to multi_user mode
alter database DatabaseNameHere set multi_User; --- Set database back to multi_user

go
Print 'Hasta La Vista Baby'

Rate

3.89 (9)

You rated this post out of 5. Change rating

Share

Share

Rate

3.89 (9)

You rated this post out of 5. Change rating