DB太大?一键帮你收缩所有DB文件大小(Shrink Files for All Databases in SQL Server)

Posted 薰薰熊的技术分享社区

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DB太大?一键帮你收缩所有DB文件大小(Shrink Files for All Databases in SQL Server)相关的知识,希望对你有一定的参考价值。

本文介绍一个简单的SQL脚本,实现收缩整个Microsoft SQL Server实例所有非系统DB文件大小的功能。

 

作为一个与SQL天天打交道的程序猿,经常会遇到DB文件太大,把空间占满的情况:

而对于开发测试人员来说,如果DB数据不是特别重要的话,不会特意扩大磁盘空间,而是直接利用SQL的Shrink File功能缩小DB文件大小,详见:https://docs.microsoft.com/en-us/sql/relational-databases/databases/shrink-a-file

 

这里介绍一个脚本,支持一键收缩整个SQL Server实例上所有非系统DB文件大小。

脚本支持功能和相关逻辑如下:

  • 五个系统DB(master、model、msdb、tempdb、Resource)不会执行Shrink File操作;
  • 如果DB的Recovery Model是FULL或者BULK_LOGGED,会自动改成SIMPLE,Shrink File操作后再改回原来的;
  • 只会对DB状态为ONLINE的DB进行Shrink File操作;
  • DB的所有文件,包括数据文件和日志文件都会被执行收缩操作(Shrink Database Data Files & Shrink Database Log Files);
  • 执行SQL脚本的用户需要有sysadmin或者相关数据库的DBO权限。

脚本如下:

 1 -- Created by Bob from http://www.cnblogs.com/lavender000/
 2 use master
 3 DECLARE dbCursor CURSOR for select name from [master].[sys].[databases] where state = 0 and is_in_standby = 0;
 4 DECLARE @dbname NVARCHAR(255)
 5 DECLARE @recoveryModel NVARCHAR(255)
 6 DECLARE @tempTSQL NVARCHAR(255)
 7 DECLARE @dbFilesCursor CURSOR
 8 DECLARE @dbFile NVARCHAR(255)
 9 DECLARE @flag BIT
10 
11 OPEN dbCursor
12 FETCH NEXT FROM dbCursor INTO @dbname
13 
14 WHILE @@FETCH_STATUS = 0
15 BEGIN
16     if((@dbname <> \'master\') and (@dbname <> \'model\') and (@dbname <> \'msdb\') and (@dbname <> \'tempdb\') and (@dbname <> \'Resource\'))
17     begin
18         print(\'\')
19         print(\'Database [\' + @dbname + \'] will be shrinked log...\')
20         SET @flag = 1
21         SET @recoveryModel = (SELECT recovery_model_desc FROM sys.databases WHERE name = @dbname)
22         if((@recoveryModel = \'FULL\') or (@recoveryModel = \'BULK_LOGGED\'))
23         begin
24             SET @tempTSQL = (select CONCAT(\'ALTER DATABASE [\', @dbname, \'] SET RECOVERY SIMPLE with no_wait\'))
25             EXEC sp_executesql @tempTSQL
26             if (@@ERROR = 0)
27             begin
28                 print(\'    Database [\' + @dbname + \'] recovery model has been changed to \'\'SIMPLE\'\'.\')
29                 SET @flag = 1
30             end
31             else
32             begin
33                 print(\'Database [\' + @dbname + \'] recovery model failed to be changed to \'\'SIMPLE\'\'.\')
34                 SET @flag = 0
35             end
36         end
37 
38         if(@flag = 1)
39         begin
40             SET @tempTSQL = (select CONCAT(\'use [\', @dbname, \']\'))
41             EXEC sp_executesql @tempTSQL            
42             SET @dbFilesCursor = CURSOR for select sys.master_files.name from sys.master_files, [master].[sys].[databases] where databases.name = @dbname and databases.database_id = sys.master_files.database_id
43             open @dbFilesCursor
44             FETCH NEXT FROM @dbFilesCursor INTO @dbFile
45             WHILE @@FETCH_STATUS = 0
46             BEGIN
47                 SET @tempTSQL = (select CONCAT(\'use [\', @dbname, \'] DBCC SHRINKFILE (N\'\'\', @dbFile, \'\'\') with NO_INFOMSGS\'))
48                 EXEC sp_executesql @tempTSQL
49                 if(@@ERROR = 0)    print(\'        Database file [\' + @dbFile + \'] has been shrinked log successfully.\')
50                 FETCH NEXT FROM @dbFilesCursor INTO @dbFile
51             END
52             CLOSE @dbFilesCursor
53             DEALLOCATE @dbFilesCursor
54 
55             if(@recoveryModel <> \'SIMPLE\')
56             begin
57                 -- Finally changed back
58                 SET @tempTSQL = (select CONCAT(\'ALTER DATABASE [\', @dbname, \'] SET RECOVERY \', @recoveryModel, \' with no_wait\'))
59                 EXEC sp_executesql @tempTSQL
60                 if (@@ERROR = 0)
61                 begin
62                     print(\'    Database [\' + @dbname + \'] recovery model has been changed back to \'\'\' + @recoveryModel + \'\'\'\')
63                 end
64                 else 
65                 begin
66                     print(\'    Database [\' + @dbname + \'] recovery model failed to be changed back to \'\'\' + @recoveryModel + \'\'\'\')
67                 end
68             end
69         end
70     end
71 FETCH NEXT FROM dbCursor INTO @dbname
72 END
73 
74 CLOSE dbCursor
75 DEALLOCATE dbCursor

执行完效果如下:

 

Note:

  • 如果不放心使用,可提前备份相关数据库;
  • 使用前请仔细阅读脚本支持功能和相关逻辑,如与自己需求不符,请不要使用该脚本,或者请根据自己需求自行修改脚本;
  • 脚本为简易脚本,仅用于测试学习,可能有BUG,不可生产环境使用,如有错误,请留言。

 

更新:该脚本在SQL Server 2008R2上执行可能会报如下错误:

\'CONCAT\' is not a recognized built-in function name.

由于脚本中使用了CONCAT函数,该函数是TSQL在SQL Server 2012中新引入的函数,具体详见:https://docs.microsoft.com/en-us/sql/t-sql/functions/concat-transact-sql

因此如果想在SQL Server 2012以下版本中使用的话需要把CONCAT函数改成string +方法,具体如下:

 1 -- Created by Bob from http://www.cnblogs.com/lavender000/
 2 use master
 3 DECLARE dbCursor CURSOR for select name from [master].[sys].[databases] where state = 0 and is_in_standby = 0;
 4 DECLARE @dbname NVARCHAR(255)
 5 DECLARE @recoveryModel NVARCHAR(255)
 6 DECLARE @tempTSQL NVARCHAR(255)
 7 DECLARE @dbFilesCursor CURSOR
 8 DECLARE @dbFile NVARCHAR(255)
 9 DECLARE @flag BIT
10 
11 OPEN dbCursor
12 FETCH NEXT FROM dbCursor INTO @dbname
13 
14 WHILE @@FETCH_STATUS = 0
15 BEGIN
16     if((@dbname <> \'master\') and (@dbname <> \'model\') and (@dbname <> \'msdb\') and (@dbname <> \'tempdb\') and (@dbname <> \'Resource\'))
17     begin
18         print(\'\')
19         print(\'Database [\' + @dbname + \'] will be shrinked log...\')
20         SET @flag = 1
21         SET @recoveryModel = (SELECT recovery_model_desc FROM sys.databases WHERE name = @dbname)
22         if((@recoveryModel = \'FULL\') or (@recoveryModel = \'BULK_LOGGED\'))
23         begin
24             SET @tempTSQL = (\'ALTER DATABASE [\' + @dbname + \'] SET RECOVERY SIMPLE with no_wait\')
25             EXEC sp_executesql @tempTSQL
26             if (@@ERROR = 0)
27             begin
28                 print(\'    Database [\' + @dbname + \'] recovery model has been changed to \'\'SIMPLE\'\'.\')
29                 SET @flag = 1
30             end
31             else
32             begin
33                 print(\'Database [\' + @dbname + \'] recovery model failed to be changed to \'\'SIMPLE\'\'.\')
34                 SET @flag = 0
35             end
36         end
37 
38         if(@flag = 1)
39         begin
40             SET @tempTSQL = (\'use [\' + @dbname + \']\')
41             EXEC sp_executesql @tempTSQL            
42             SET @dbFilesCursor = CURSOR for select sys.master_files.name from sys.master_files, [master].[sys].[databases] where databases.name = @dbname and databases.database_id = sys.master_files.database_id
43             open @dbFilesCursor
44             FETCH NEXT FROM @dbFilesCursor INTO @dbFile
45             WHILE @@FETCH_STATUS = 0
46             BEGIN
47                 SET @tempTSQL = (\'use [\' + @dbname + \'] DBCC SHRINKFILE (N\'\'\' + @dbFile + \'\'\') with NO_INFOMSGS\')
48                 EXEC sp_executesql @tempTSQL
49                 if(@@ERROR = 0)    print(\'        Database file [\' + @dbFile + \'] has been shrinked log successfully.\')
50                 FETCH NEXT FROM @dbFilesCursor INTO @dbFile
51             END
52             CLOSE @dbFilesCursor
53             DEALLOCATE @dbFilesCursor
54 
55             if(@recoveryModel <> \'SIMPLE\')
56             begin
57                 -- Finally changed back
58                 SET @tempTSQL = (\'ALTER DATABASE [\' + @dbname + \'] SET RECOVERY \' + @recoveryModel + \' with no_wait\')
59                 EXEC sp_executesql @tempTSQL
60                 if (@@ERROR = 0)
61                 begin
62                     print(\'    Database [\' + @dbname + \'] recovery model has been changed back to \'\'\' + @recoveryModel + \'\'\'\')
63                 end
64                 else 
65                 begin
66                     print(\'    Database [\' + @dbname + \'] recovery model failed to be changed back to \'\'\' + @recoveryModel + \'\'\'\')
67                 end
68             end
69         end
70     end
71 FETCH NEXT FROM dbCursor INTO @dbname
72 END
73 
74 CLOSE dbCursor
75 DEALLOCATE dbCursor

给大家带来的不变深表歉意。

 

[原创文章,转载请注明出处,仅供学习研究之用,如有错误请留言,谢谢支持]

[原站点:http://www.cnblogs.com/lavender000/p/6882741.html,来自永远薰薰]

以上是关于DB太大?一键帮你收缩所有DB文件大小(Shrink Files for All Databases in SQL Server)的主要内容,如果未能解决你的问题,请参考以下文章

代码:306。DB::Exception:从 localhost:9000 接收。 DB::Exception:堆栈大小太大。堆栈地址

db2数据库表数据量太大如何横向拆分

Excel表格太大,无法同时打印在一张纸上?一键帮你轻松搞定!

Sqlite DB 文件太大....?

收缩Oracle数据文件

SQL Server 压缩日志及数据库文件大小