SQL - shrink database log file

丶灬走出姿态 提交于 2019-12-01 07:15:42

问题


I am trying to shrink my database log file. I have tried to run:

USE databasename 
BACKUP log databasename
WITH truncate_only 
DBCC shrinkfile (databasename_log, 1)

I get the error message:

Msg 155, Level 15, State 1, Line 3 'truncate_only' is not a recognized BACKUP option.

Am I missing something?


回答1:


SQL Server 2008 no longer allows the NO_LOG / TRUNCATE_ONLY options.

To truncate your transaction log, you either have to back it up (for real) or switch the database's Recovery Model to Simple. The latter is probably what you really want here. You don't need Full recovery unless you are making regular transaction log backups to be able to restore to some point mid-day.




回答2:


I think the best way is to use a script like this:

USE AdventureWorks
GO

-- Use some dynamic SQL just only not to re-write several times the name 
-- of your db, or to insert this snippet into a loop for all your databases...
DECLARE @dbname varchar(50) = 'AdventureWorks';
DECLARE @logFileName varchar(50) = @dbname  + '_log';
DECLARE @SQL nvarchar(max);
SET @SQL = REPLACE('ALTER DATABASE {dbname} SET RECOVERY FULL;', '{dbname}', @dbname);
EXECUTE(@SQL);

DECLARE @path nvarchar(255) = N'F:\BCK_DB\logBCK' + CONVERT(CHAR(8), GETDATE(), 112) + '_'
  + REPLACE(CONVERT(CHAR(8), GETDATE(), 108),':','') + '.trn';

BACKUP LOG @dbname TO DISK = @path WITH INIT, COMPRESSION;

DBCC SHRINKFILE(@logFileName);

-- determine here the new file size and growth rate:
SET @SQL = REPLACE('ALTER DATABASE {dbname} MODIFY FILE (NAME = ' + @logFileName + ', SIZE = 32000MB, FILEGROWTH = 10%);', 
    '{dbname}', @dbname);
EXECUTE(@SQL);
GO

http://www.snip2code.com/Snippet/12913/How-to-correctly-Shrink-Log-File-for-SQL



来源:https://stackoverflow.com/questions/2196151/sql-shrink-database-log-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!