Home MS SQL Server DB Maintenance Backup and Truncate Transaction Logs
Backup and Truncate Transaction Logs E-mail
Written by Administrator   
Tuesday, 16 December 2008 09:12

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'

 

source: http://www.sqlservercentral.com/scripts/Backup/65024/


Last Updated on Monday, 29 December 2008 15:53