sqlServer 收缩日志大小

declare @dbName nvarchar(50)
declare @bakdbPath nvarchar(255)
declare @bakLogPath nvarchar(255)
declare @LogName nvarchar(50)
set @dbName=’HNBC_NEW20191008′
set @bakdbPath =’D:\DataBase\log\’+@dbName+’.bak’
set @bakLogPath =’D:\DataBase\log\’+@dbName+’_log.bak’

use HNBC_NEW20191008–use 没法用参数所以只能是数据库名称

–1、获取收缩的日志名称
set @LogName=(select name from sys.database_files where type_desc=’log’)
print  @LogName

–2、日志收缩之前完整备份数据库数据文件和日志文件,方便恢复
use master
exec sp_executesql N’ backup database @dbName to disk=@bakdbPath’,N’@dbName nvarchar(50),@bakdbPath nvarchar(255)’,@dbName,@bakdbPath
exec sp_executesql N’backup log @dbName to disk=@bakLogPath’,N’@dbName nvarchar(50),@bakLogPath nvarchar(255)’,@dbName,@bakLogPath

–3、将“恢复模式”设置为“简单”
exec(‘ALTER DATABASE ‘+@dbname+’ SET RECOVERY SIMPLE’)

–4、收缩日志文件大小到1M
use HNBC_NEW20191008 –use 没法用参数所以只能是数据库名称
execute(N’DBCC SHRINKFILE (‘+@LogName+’ , 1, TRUNCATEONLY)’)

–5、将“恢复模式”设置为“完整”
USE master
execute( N’ALTER DATABASE ‘+ @dbName+’ SET RECOVERY FULL WITH NO_WAIT’)
execute( N’ALTER DATABASE ‘+ @dbName+’ SET RECOVERY FULL’)
GO

–下面是恢复命令
–restore database  HNBC_NEW20191008 from  disk=’D:\DataBase\log\HNBC_NEW20191008.bak’  with replace,norecovery
–restore log HNBC_NEW20191008 from disk=’D:\DataBase\log\HNBC_NEW20191008_log.bak’ with replace
 

    原文作者:智者长存
    原文地址: https://blog.csdn.net/liufeifeinanfeng/article/details/103200109
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞