sqlserver

YQWTX-G8T4R-QW4XX-BVH62-GP68Y

 

FH666-Y346V-7XFQ3-V69JM-RHW28

 

压缩数据库

USE [master]


------------遍历所有用户数据库 进行日志清理-------------------------------------------------------------------
DECLARE @SQL AS NVARCHAR(4000)
DECLARE @DATABaseName AS NVARCHAR(50)


DECLARE My_Cursor CURSOR --定义游标
FOR
( SELECT NAME
FROM sys.databases
WHERE NAME NOT IN ( 'master', 'msdb', 'tempdb', 'model',
'ReportServerTempDB', 'ReportServer' )
)
--查出需要的集合放到游标中
OPEN My_Cursor;
--打开游标
FETCH NEXT FROM My_Cursor INTO @DATABaseName;
--读取第一行数据
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = '
USE ' + @DATABaseName + '


--查询出数据库对应的日志文件名称
DECLARE @strDBName AS NVARCHAR(500)
DECLARE @strLogName AS NVARCHAR(500)
DECLARE @strSQL AS VARCHAR(1000)

DECLARE @DBLogSise AS INT = 2

SELECT @strLogName = B.name,
@strDBName = A.name
FROM MASTER.sys.databases AS A
INNER JOIN sys.master_files AS B
ON A.database_id = B.database_id
WHERE A.database_id = DB_ID()

SET @strSQL = ''
--设置数据库恢复模式为简单
ALTER DATABASE ['' + @strDBName +
''] SET RECOVERY SIMPLE;
--收缩日志文件
DBCC SHRINKFILE ('' + @strLogName + '' , '' + CONVERT(VARCHAR(20), @DBLogSise)
+ '');
--恢复数据库还原模式为完整
ALTER DATABASE ['' + @strDBName + ''] SET RECOVERY FULL ''


EXEC (@strSQL)

 

'

EXEC (@SQL)
PRINT '清理' + @DATABaseName + '日志完成'

FETCH NEXT FROM My_Cursor INTO @DATABaseName; --读取下一行数据
END
CLOSE My_Cursor;
--关闭游标
DEALLOCATE My_Cursor;
--释放游标


PRINT '-----------清理日志完成---------------------'
+ CONVERT(VARCHAR(100), GETDATE(), 126) + '----------'

posted @ 2018-03-28 09:54  温柔牛  阅读(132)  评论(0编辑  收藏  举报