--縮小sql日志
-- exec p_compdb 'test'
create proc p_compdb
@dbname sysname, --要壓縮的數(shù)據(jù)庫名
@bkdatabase bit=1, --因?yàn)榉蛛x日志的步驟中,可能會(huì)損壞數(shù)據(jù)庫,所以你可以選擇是否自動(dòng)數(shù)據(jù)庫
@bkfname nvarchar(260)='' --備份的文件名,如果不指定,自動(dòng)備份到默認(rèn)備份目錄,備份文件名為:數(shù)據(jù)庫名+日期時(shí)間
as
--1.清空日志
exec('dump transaction ['[email protected]+'] with no_log')
--2.截?cái)嗍聞?wù)日志:
exec('backup log ['[email protected]+'] with no_log')
--3.收縮數(shù)據(jù)庫文件(如果不壓縮,數(shù)據(jù)庫的文件不會(huì)減小
exec('dbcc shrinkdatabase(['[email protected]+'])')
--4.設(shè)置自動(dòng)收縮
exec('exec sp_dboption '''[email protected]+''',''autoshrink'',''true''')
--后面的步驟有一定危險(xiǎn),你可以可以選擇是否應(yīng)該這些步驟
--5.分離數(shù)據(jù)庫
if @bkdatabase=1
begin
if isnull(@bkfname,'')=''
set @[email protected]+'_'+convert(varchar,getdate(),112)
+replace(convert(varchar,getdate(),108),':','')
select 提示信息='備份數(shù)據(jù)庫到sql 默認(rèn)備份目錄,備份文件名:'[email protected]
exec('backup database ['[email protected]+'] to disk='''[email protected]+'''')
end
--進(jìn)行分離處理
create table #t(fname nvarchar(260),type int)
exec('insert into #t select filename,type=status&0x40 from ['[email protected]+']..sysfiles')
exec('sp_detach_db '''[email protected]+'''')
--刪除日志文件
declare @fname nvarchar(260),@s varchar(8000)
declare tb cursor local for select fname from #t where type=64
open tb
fetch next from tb into @fname
while @@fetch_status=0
begin
set @s='del "'+rtrim(@fname)+'"'
exec master..xp_cmdshell @s,no_output
fetch next from tb into @fname
end
close tb
deallocate tb
--附加數(shù)據(jù)庫
set @s=''
declare tb cursor local for select fname from #t where type=0
open tb
fetch next from tb into @fname
while @@fetch_status=0
begin
set @[email protected]+','''+rtrim(@fname)+''''
fetch next from tb into @fname
end
close tb
deallocate tb
exec('sp_attach_single_file_db '''[email protected]+''''[email protected])
go