縮小SQL SERVER日志文件
2024-08-31 00:48:11
供稿:網友
 
,歡迎訪問網頁設計愛好者web開發。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