当前位置: 首页 > 图文教程 > 数据库 > MSSQL > 缩小SQL Server数据库日志

MSSQL
SQL Server 2005查看文件及文件组的语句
用最简单的步骤备份SQL数据库的文件到本地
在SQL Server数据库中拆分字符串函数
SQL Server数据库维度表和事实表概述
Microsoft SQL Server数据库日志截断
SQL Server 2000 SP4与数据链接池问题
SQL Server游标使用实例
SQL Server 2008:传递表值参数
微软SQL Server 2008令商业智能平民化
将SQL2000数据库升级到SQL2005
在SQL Server2005中进行错误捕捉
动态SQL语句的编程
SQL Server 2008升级报表服务器数据库
在SAN上创建SQL Server群集
SQL查询中的转义序列不对的解决办法
SQL2005一个不起眼但很实用的函数
管理SQL Server数据库和应用元数据
选择SQL Server恢复模型确保正确备份
查看SQL执行计划常用方法
SQL2008增强的集成开发环境

MSSQL 中的 缩小SQL Server数据库日志


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-30   浏览: 112 ::
收藏到网摘: n/a

 
--缩小日志
-- exec p_compdb ’test’ 
create proc p_compdb
@dbname sysname, --要压缩的数据库名
@bkdatabase bit=1, --因为分离日志的步骤中,可能会损坏数据库,所以你可以选择是否自动数据库
@bkfname nvarchar(260)=’’ --备份的文件名,如果不指定,自动备份到默认备份目录,备份文件名为:数据库名+日期时间
as
--1.清空日志
exec(’DUMP TRANSACTION [’+@dbname+’] WITH  NO_LOG’)
--2.截断事务日志:
exec(’BACKUP LOG [’+@dbname+’] WITH NO_LOG’)
--3.收缩数据库文件(如果不压缩,数据库的文件不会减小
exec(’DBCC SHRINKDATABASE([’+@dbname+’])’)
--4.设置自动收缩
exec(’EXEC sp_dboption ’’’+@dbname+’’’,’’autoshrink’’,’’TRUE’’’)
--后面的步骤有一定危险,你可以可以选择是否应该这些步骤
--5.分离数据库
if @bkdatabase=1
begin
if isnull(@bkfname,’’)=’’ 
set @bkfname=@dbname+’_’+convert(varchar,getdate(),112)
+replace(convert(varchar,getdate(),108),’:’,’’)
select 提示信息=’备份数据库到SQL 默认备份目录,备份文件名:’+@bkfname
exec(’backup database [’+@dbname+’] to disk=’’’+@bkfname+’’’’)
end
--进行分离处理
create table #t(fname nvarchar(260),type int)
exec(’insert into #t select filename,type=status&0x40 from [’+@dbname+’]..sysfiles’)
exec(’sp_detach_db ’’’+@dbname+’’’’)
--删除日志文件
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
--附加数据库
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 @s=@s+’,’’’+rtrim(@fname)+’’’’
fetch next from tb into @fname
end
close tb
deallocate tb
exec(’sp_attach_single_file_db ’’’+@dbname+’’’’+@s)
GO