DB太大?一鍵幫你收縮全部DB文件大小(Shrink Files for All Databases in SQL Server)

本文介紹一個簡單的SQL腳本,實現收縮整個Microsoft SQL Server實例全部非系統DB文件大小的功能。html

 

做爲一個與SQL每天打交道的程序猿,常常會遇到DB文件太大,把空間佔滿的狀況:sql

而對於開發測試人員來講,若是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

執行完效果以下:ui

 

Note:spa

  • 若是不放心使用,可提早備份相關數據庫;
  • 使用前請仔細閱讀腳本支持功能和相關邏輯,如與本身需求不符,請不要使用該腳本,或者請根據本身需求自行修改腳本;
  • 腳本爲簡易腳本,僅用於測試學習,可能有BUG,不可生產環境使用,若有錯誤,請留言。

 

更新:該腳本在SQL Server 2008R2上執行可能會報以下錯誤:日誌

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

因爲腳本中使用了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,來自永遠薰薰]

相關文章
相關標籤/搜索