"bat file" to run SQL log file shrink task - sql-server

I have a SQL2012 DB that has a log file growing very rapidly. I have a 3rd party program doing full database backups so I'm not worried about that.
I have the command to run in the SQL manager to shrink the log file and that is working but it's a very manual task.
I'm trying to create a script that I can schedule to run every 2 weeks but a BAT file won't work it seems as after the sqlcmd -S servername\instancename -E command is run it just goes to 1> and stops. I need to run the USE and DBCC commands but not sure how to achieve this.
I have tried looking online but nowhere can I find a way to make a double click script to run this DBCC SHRINKFILE task.
So using sqlcmd, I can do this:
USE DBNAME
GO
DBCC SHRINKFILE (DBNAME_20070302091322_Log, 1);
GO
Running manually the file shrinks to below 10mb and that is correct. I need to just automate this task.

I have a SQL2012 DB that has a log file growing very rapidly
In this case you must verify the database recovery model and log_reuse_wait_desc which you can identity with following command:
Select name, recovery_model_desc, log_reuse_wait_desc
from sys.databases
If Recovery model set to FULL:
As mentioned in the comments, you must schedule LOG BACKUP at the backup tool that you are using for Full Backups, even you perform DBCC SHRINKFILE it would't shrink the size due to active portion in the log file, you must perform appropriate action bases on log_reuse_wait_desc status before running DBCC SHRINKFILE command. You can verify it
looking at message section once DBCC command you executed.
For more details on LOG FILE/CHECKPOINTS/log_reuse_wait..
If Recovery model set to Simple:
Once you decided to go with Simple recovery model, shrink the file manually, but keep enough room for SQL Engine to perform log operations depending on transaction workload. Shrinking the log file to lower size means putting unnecessary overload on the server as the SQL Engine try to increase it again when there is no enough space available for the transaction workload/throughput.
You do not have schedule LOG backup in simple recovery model, as the log file checkpoints would be automatically added and based on checkpoint log would be truncated.

So looks like with your help i managed to get it working.
I have a BAT with the -i option where the DBCC command is.
here is that bat
sqlcmd -S sqlserver\instance -E -d databasename -i c:\test.sql -o c:\out.txt
here is hte test.sql
USE databasename
GO
DBCC SHRINKFILE (DBLOGFILENAME_Log, 1);
GO
tested and its working.

Related

Percent Log Used above threshold

Alert: The SQL Server performance counter 'Percent Log Used' (instance 'dbname') of object 'SQLServer:Databases' is now above the threshold
I tried the following:
backup log dbname with truncate_only
BACKUP LOG dbname WITH TRUNCATE_ONLY
shrink the log file using dbcc shrinkfile
DBCC SHRINKFILE(dbname_log, 1)
I am using sipmle recovery model, please suggest
You cannot take log backup when u are in SIMPLE Recover Mode. In Simple mode, this percent log growth issue will not arise altogether

Truncate SQL Server transaction log file

In my local C: drive I have a ldf file for a database that is hosted on one of our servers. I have a local copy of one of the databases that is 1 gb and a ldf (log file) of that database that is 16gb. It is eating up a lot of my local space on my hard drive. I would like to truncate that file. A lot of what I read online is don't, but it seems that they are talking about files on the server that the database is on. That isn't the case here, it is on my local machine.
The location of the file on my machine is:
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA
How come I have a copy of that log file locally and also that database locally?
How would I go about truncating this file?
Thanks!
Go to the Object Explorer pane in SSMS and right click on the database in question. Choose tasks -> shrink -> files. Change the file type option to Log, click the "Reorganize pages before releasing unused space" option, and set the value to 1 MB. Hit OK.
If this doesn't work, check to see if your database is set up with a Full database recover model. Right click the database and go to properties. Choose Options, and check the Recover model option. Set to simple (if you can!!!), then shrink the logs.
The another option you can try is to use WITH TRUNCATE_ONLY:
BACKUP LOG databasename WITH TRUNCATE_ONLY
DBCC SHRINKFILE ( adventureworks_Log, 1)
but don't try this option in live environment, the far better option is to set database in simple recovery. see the below command to do this:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (adventureworks_Log, 1)

How to Shrink Transaction log in sql server database in replication

Hi I'm having a production database and its replicated report database. How to shrink the transaction log files in the production database as the log file size is increasing. I had tried DBCC SHRINKFILE and SHRINKDATABASE commands but it does not work for me. I can't detach and shrink and attach back as the db in replication. Please help me in this issue.
First check what is causing your database to not shrink by running:
SELECT name, log_reuse_wait_desc FROM sys.DATABASES
If you are blocked by a transaction, find which one with:
DBCC OPENTRAN
Kill the transaction and shrink your db.
If the cause of the blocking is 'REPLICATION' and you are sure that your replicas are in sync, you might need to reset the status of replicated transactions. To see the status of what the database still think needs to be replicated use:
DBCC loginfo
You can reset this by first turning the Reader agent off (I usually just turn the whole SQL Server Agent off), and then run that query on the database for which you want to fix the replication issue:
EXEC sp_repldone #xactid = NULL, #xact_segno = NULL, #numtrans = 0, #time= 0, #reset = 1
Close the connection where you executed that query and restart SQL Server Agent (or just the Reader Agent). You should be all set to shrink your db now.
The database won't let you remove transaction data that isn't backed up. First you have to back up the transaction log, then you can shrink it.
Do you have a regular backup schedule in place?
If not, I suggest you read this excellent article: 8 Steps to better Transaction Log throughput
Shrink the logfile with dbcc shrinkfile
Then truncate the log file using
Backup databaseName with truncate_only
Then shrink the logfile again
I used Red-Gate's SQL Backup tool to take care of the backing up. Then I just use the management console to issue a shrink command on the log file (telling it to rearrange the pages before releasing unused space).
Works like a charm.

Why can't I shrink a transaction log file, even after backup?

I have a database that has a 28gig transaction log file. Recovery mode is simple. I just took a full backup of the database, and then ran both:
backup log dbmcms with truncate_only
DBCC SHRINKFILE ('Wxlog0', TRUNCATEONLY)
The name of the db is db_mcms and the name of the transaction log file is Wxlog0.
Neither has helped. I'm not sure what to do next.
Thank you to everyone for answering.
We finally found the issue. In sys.databases, log_reuse_wait_desc was equal to 'replication'. Apparently this means something to the effect of SQL Server waiting for a replication task to finish before it can reuse the log space.
Replication has never been used on this DB or this server was toyed with once upon a time on this db. We cleared the incorrect state by running sp_removedbreplication. After we ran this, backup log and dbcc shrinkfile worked just fine.
Definitely one for the bag-of-tricks.
Sources:
http://social.technet.microsoft.com/Forums/pt-BR/sqlreplication/thread/34ab68ad-706d-43c4-8def-38c09e3bfc3b
http://www.eggheadcafe.com/conversation.aspx?messageid=34020486&threadid=33890705
You may run into this problem if your database is set to autogrow the log & you end up with lots of virtual log files.
Run DBCC LOGINFO('databasename') & look at the last entry, if this is a 2 then your log file wont shrink. Unlike data files virtual log files cannot be moved around inside the log file.
You will need to run BACKUP LOG and DBCC SHRINKFILE several times to get the log file to shrink.
For extra bonus points run DBBC LOGINFO in between log & shirks
'sp_removedbreplication' didn't solve the issue for me as SQL just returned saying that the Database wasn't part of a replication...
I found my answer here:
http://www.sql-server-performance.com/forum/threads/log-file-fails-to-truncate.25410/
http://blogs.msdn.com/b/sqlserverfaq/archive/2009/06/01/size-of-the-transaction-log-increasing-and-cannot-be-truncated-or-shrinked-due-to-snapshot-replication.aspx
Basically I had to create a replication, reset all of the replication pointers to Zero; then delete the replication I had just made.
i.e.
Execute SP_ReplicationDbOption {DBName},Publish,true,1
GO
Execute sp_repldone #xactid = NULL, #xact_segno = NULL, #numtrans = 0, #time = 0, #reset = 1
GO
DBCC ShrinkFile({LogFileName},0)
GO
Execute SP_ReplicationDbOption {DBName},Publish,false,1
GO
Don't you need this
DBCC SHRINKFILE ('Wxlog0', 0)
Just be sure that you are aware of the dangers: see here: Do not truncate your ldf files!
And here Backup Log with Truncate_Only: Like a Bear Trap
This answer has been lifted from here and is posted here in case the other thread gets deleted:
The fact that you have non-distributed LSN in the log is the problem.
I have seen this once before not sure why we dont unmark the
transaction as replicated. We will investigate this internally. You
can execute the following command to unmark the transaction as
replicated
EXEC sp_repldone #xactid = NULL, #xact_segno = NULL, #numtrans = 0, #time = 0, #reset = 1
At this point you should be able to truncate the log.
I've had the same issue in the past. Normally a shrink and a trn backup need to occur multiple times. In extreme cases I set the DB to "Simple" recovery and then run a shrink operation on the log file. That always works for me. However recently I had a situation where that would not work. The issue was caused by a long running query that did not complete, so any attempts to shrink were useless until I could kill that process then run my shrink operations. We are talking a log file that grew to 60 GB and is now shrunk to 500 MB.
Remember, as soon as you change from FULL to Simple recovery mode and do the shrink, dont forget to set it back to FULL. Then immediately afterward you must do a FULL DB backup.
If you set the recovery mode on the database in 2005 (don't know for pre-2005) it will drop the log file all together and then you can put it back in full recovery mode to restart/recreate the logfile. We ran into this with SQL 2005 express in that we couldn't get near the 4GB limit with data until we changed the recovery mode.
I know this is a few years old, but wanted to add some info.
I found on very large logs, specifically when the DB was not set to backup transaction logs (logs were very big), the first backup of the logs would not set log_reuse_wait_desc to nothing but leave the status as still backing up. This would block the shrink. Running the backup a second time properly reset the log_reuse_wait_desc to NOTHING, allowing the shrink to process.
Have you tried from within SQL Server management studio with the GUI. Right click on the database, tasks, shrink, files. Select filetype=Log.
I worked for me a week ago.
Try creating another full backup after you backup the log w/ truncate_only (IIRC you should do this anyway to maintain the log chain). In simple recovery mode, your log shouldn't grow much anyway since it's effectively truncated after every transaction. Then try specifying the size you want the logfile to be, e.g.
-- shrink log file to c. 1 GB
DBCC SHRINKFILE (Wxlog0, 1000);
The TRUNCATEONLY option doesn't rearrange the pages inside the log file, so you might have an active page at the "end" of your file, which could prevent it from being shrunk.
You can also use DBCC SQLPERF(LOGSPACE) to make sure that there really is space in the log file to be freed.
Try to use target size you need insted of TRUNCATEONLY in DBCC:
DBCC SHRINKFILE ('Wxlog0', 1)
And check this to articles:
http://msdn.microsoft.com/en-us/library/ms189493(SQL.90).aspx
http://support.microsoft.com/kb/907511
Edit:
You can try to move allocated pages to the beginning of the log file first with
DBCC SHRINKFILE ('Wxlog0', NOTRUNCATE)
and after that
DBCC SHRINKFILE ('Wxlog0', 1)
Put the DB back into Full mode, run the transaction log backup (not just a full backup) and then the shrink.
After it's shrunk, you can put the DB back into simple mode and it txn log will stay the same size.
I had the same problem. I ran an index defrag process but the transaction log became full and the defrag process errored out. The transaction log remained large.
I backed up the transaction log then proceeded to shrink the transaction log .ldf file. However the transaction log did not shrink at all.
I then issued a "CHECKPOINT" followed by "DBCC DROPCLEANBUFFER" and was able to shrink the transaction log .ldf file thereafter
You cannot shrink a transaction log smaller than its initially created size.
I tried all the solutions listed and none of them worked. I ended up having to do a sp_detach_db, then deleting the ldf file and re-attaching the database forcing it to create a new ldf file. That worked.

What is the command to truncate a SQL Server log file?

I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?
In management studio:
Don't do this on a live environment, but to ensure you shrink your dev db as much as you can:
Right-click the database, choose Properties, then Options.
Make sure "Recovery model" is set to "Simple", not "Full"
Click OK
Right-click the database again, choose Tasks -> Shrink -> Files
Change file type to "Log"
Click OK.
Alternatively, the SQL to do it:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (mydatabase_Log, 1)
Ref: http://msdn.microsoft.com/en-us/library/ms189493.aspx
if I remember well... in query analyzer or equivalent:
BACKUP LOG databasename WITH TRUNCATE_ONLY
DBCC SHRINKFILE ( databasename_Log, 1)
For SQL Server 2008, the command is:
ALTER DATABASE ExampleDB SET RECOVERY SIMPLE
DBCC SHRINKFILE('ExampleDB_log', 0, TRUNCATEONLY)
ALTER DATABASE ExampleDB SET RECOVERY FULL
This reduced my 14GB log file down to 1MB.
For SQL 2008 you can backup log to nul device:
BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10
And then use DBCC SHRINKFILE to truncate the log file.
backup log logname with truncate_only followed by a dbcc shrinkfile command
Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:
BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)
Another option altogether is to detach the database via Management Studio. Then simply delete the log file, or rename it and delete later.
Back in Management Studio attach the database again. In the attach window remove the log file from list of files.
The DB attaches and creates a new empty log file. After you check everything is all right, you can delete the renamed log file.
You probably ought not use this for production databases.

Resources