大家好我曾写过一个收缩数据库的脚本
DECLARE @string NVARCHAR(4000),
@Strt INT ,
@END INT ,
@DBName NVARCHAR(255),
@Log_Size DECIMAL(18,5),
@Log_Name NVARCHAR(25),
@String_sql NVARCHAR(MAX)
CREATE TABLE #t (srno INT IDENTITY(1,1),filename NVARCHAR(255),DBNAME NVARCHAR(50))
CREATE TABLE #Tmp_logfile (fileName NVARCHAR(25),file_size DECIMAL(12,5),log_Name NVARCHAR(25))
INSERT INTO #Tmp_logfile (fileName,file_size,log_Name)
SELECT a.NAME , CONVERT(DECIMAL(12,5),ROUND(b.size/128.000,5)),b.name
FROM SYS.DATABASES a
INNER JOIN SYS.MASTER_FILES b ON a.database_id=b.database_id
WHERE a.database_id > 4 AND b.file_id =2
INSERT INTO #t
SELECT
'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
+ 'DBCC SHRINKFILE (N''' + mf.name + N''' , 1, TRUNCATEONLY) '
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) as fileName,d.name
FROM sys.master_files mf
JOIN sys.databases d
ON mf.database_id = d.database_id
WHERE d.database_id > 4 AND mf.file_id=2;
SET @Strt=1
SELECT @END= Max(Srno)FROM #t
While @Strt<=@END
BEGIN
SELECT @string= FileName,@DBName= DBNAME FROM #t WHERE srno= @Strt
SELECT @Log_Size= file_size FROM #Tmp_logfile WHERE fileName= @DBName
IF @Log_Size > 10000 BEGIN -- Limit The Log Size After which Log file to be Shrink
PRINT (@string)
EXECUTE (@string)
END
SET @Strt=@Strt+1
END ---- SHRINKING Log File END Here
这里举例说明我已经把日志文件大于10 GB的条件收缩了数据库日志文件。
但问题是有时它在Sql Agent中运行时失败并不知道我犯了什么错误。任何帮助都会被感激。
答案 0 :(得分:0)
为缩小数据库创建了一个proc。它不检查日志大小。它将日志百分比检查为60.当前写为静态。
运行顺利。可以作为你的过程的替代。
Create Proc ShrinkDatabase
As
Begin
Declare @DBName nvarchar(100),@sQuery nvarchar(max)
Declare @LogFileName nvarchar(100)=''
Create table #tblTemp (id int identity(1,1),DatabaseName nvarchar(100),LogSize decimal(10,2),LogPercent decimal(10,2), IsHandled int)
Insert into #tblTemp (DatabaseName,LogSize,LogPercent,IsHandled)
Exec ('DBCC SQLPERF(logspace)');
Update #tblTemp Set IsHandled=0;
Delete from #tblTemp WHERE DatabaseName IN
('master','model','msdb','tempdb','ReportServer$MSSQLSERVER14','ReportServer$MSSQLSERVER14TempDB',
'ReportServer$SQLEXPRESS','ReportServer$SQLEXPRESSTempDB','ReportServer','ReportServerTempDB');
While (Select count(*) from #tblTemp Where LogPercent > 60 and IsHandled=0) > 0
Begin
Select Top 1 @DBName=DatabaseName from #tblTemp Where LogPercent > 60 And IsHandled=0
Set @sQuery=' USE ' + @DbName + '; '
Exec (@sQuery)
SELECT @LogFileName=name FROM sys.master_files
WHERE database_id = (Select database_id from sys.databases Where name=@DbName) AND type = 1;
Set @sQuery=@sQuery + ' ALTER DATABASE '+@DBName+' SET RECOVERY SIMPLE; '
Set @sQuery=@sQuery + ' DBCC SHRINKFILE ('+@LogFileName+') WITH NO_INFOMSGS ; '
Set @sQuery=@sQuery + ' ALTER DATABASE '+@DBName+' SET RECOVERY FULL;'
--Print (@sQuery)
Exec (@sQuery)
Print 'Shrunk Database: ' + @DBName
Update #tblTemp Set IsHandled=1 Where DatabaseName=@DbName And LogPercent > 60 And IsHandled=0
End
Drop table #tblTemp
End
Go