缩小SQL SERVER日志文件

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 svg 的 blog

sql server 2000 会有日志文件由于时间的积累越来越大的问题:数据库实际大小为15m, 日志文件实际大小为625kb(导出的日志文件), 但日志文件实际占用空间为200mb(默认设置是文件日志会自动增长)。
如果想在数据库属性那里,直接将当前的日志文件的存储空间改小,是不行的。
 
解决方法:

找到下面的代码,可以将日志文件缩小到自己想要的大小了。把代码copy到查询分析器里,,然后修改其中的3个参数(数据库名,日志文件名,和目标日志文件的大小),运行即可!

set nocount on
declare @logicalfilename sysname,
@maxminutes int,
@newsize int

use gfcms -- 要操作的数据库名
select @logicalfilename = 'gfcms_log', -- 日志文件名
@maxminutes = 10, -- limit on time allowed to wrap log.
@newsize = 100 -- 你想设定的日志文件的大小(m),注意此大小必须小于实际文件大小

-- setup / initialize
--获取原始文件大小
declare @originalsize int

select @originalsize = size
from sysfiles
where name = @logicalfilename

select 'original size of ' + db_name() + ' log is ' +
convert(varchar(30),@originalsize) + ' 8k pages or ' +
convert(varchar(30),(@originalsize*8/1024)) + 'mb'
from sysfiles
where name = @logicalfilename
create table dummytrans
(dummycolumn char (8000) not null)


declare @counter int,
@starttime datetime,
@trunclog varchar(255)
select @starttime = getdate(),
@trunclog = 'backup log ' + db_name() + ' with truncate_only'

exec (@trunclog)--把log中能够shrink的transaction的log标记为可以清除
dbcc shrinkfile (@logicalfilename, @newsize)
--shrink文件

-- wrap the log if necessary.
while @maxminutes > datediff (mi, @starttime, getdate()) -- time has not expired
and @originalsize = (select size from sysfiles where name = @logicalfilename)
and (@originalsize * 8 /1024) > @newsize
begin -- outer loop.
    select @counter = 0
    while ((@counter < @originalsize / 16) and         (@counter < 50000))
    begin -- update
        insert dummytrans values ('fill log')
        delete dummytrans
        select @counter = @counter + 1
    end
    exec (@trunclog)
end

select 'final size of ' + db_name() + ' log is ' +
convert(varchar(30),size) + ' 8k pages or ' +
convert(varchar(30),(size*8/1024)) + 'mb'
from sysfiles
where name = @logicalfilename

drop table dummytrans
set nocount off

详细解释:
关键的语句是:
'backup log ' + db_name() + ' with truncate_only'和
dbcc shrinkfile (@logicalfilename, @newsize)
 
'backup log ' + db_name() + ' with truncate_only'
在不备份日志的情况下,删除不活动的日志部分,并且截断日志。但是,截断不减小物理日志文件的大小,但减小逻辑日志文件的大小。
 
dbcc shrinkfile
收缩相关数据库的指定数据文件或日志文件大小,即减小物理日志文件的大小。
语法
dbcc shrinkfile
    ( { file_name | file_id }
        { [ , target_size ]
            | [ , { emptyfile | notruncate | truncateonly } ]
        }
    )
 
详细的描述可以参考
mk:@msitstore:c:\program%20files\microsoft%20sql%20server\80\tools\books\tsqlref.chm::/ts_dbcc_8b51.htm
 
mk:@msitstore:c:\program%20files\microsoft%20sql%20server\80\tools\books\architec.chm::/8_ar_da2_7vaf.htm
 
 
 

本文关键:缩小SQL SERVER日志文件
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top