DB太大?一鍵幫你收縮所有DB檔案大小(Shrink Files for All Databases in SQL Server)

來源:互聯網
上載者:User

標籤:png   recover   title   cut   ros   開發   ext   cat   tar   

本文介紹一個簡單的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 BIT10 11 OPEN dbCursor12 FETCH NEXT FROM dbCursor INTO @dbname13 14 WHILE @@FETCH_STATUS = 015 BEGIN16     if((@dbname <> ‘master‘) and (@dbname <> ‘model‘) and (@dbname <> ‘msdb‘) and (@dbname <> ‘tempdb‘) and (@dbname <> ‘Resource‘))17     begin18         print(‘‘)19         print(‘Database [‘ + @dbname + ‘] will be shrinked log...‘)20         SET @flag = 121         SET @recoveryModel = (SELECT recovery_model_desc FROM sys.databases WHERE name = @dbname)22         if((@recoveryModel = ‘FULL‘) or (@recoveryModel = ‘BULK_LOGGED‘))23         begin24             SET @tempTSQL = (select CONCAT(‘ALTER DATABASE [‘, @dbname, ‘] SET RECOVERY SIMPLE with no_wait‘))25             EXEC sp_executesql @tempTSQL26             if (@@ERROR = 0)27             begin28                 print(‘    Database [‘ + @dbname + ‘] recovery model has been changed to ‘‘SIMPLE‘‘.‘)29                 SET @flag = 130             end31             else32             begin33                 print(‘Database [‘ + @dbname + ‘] recovery model failed to be changed to ‘‘SIMPLE‘‘.‘)34                 SET @flag = 035             end36         end37 38         if(@flag = 1)39         begin40             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_id43             open @dbFilesCursor44             FETCH NEXT FROM @dbFilesCursor INTO @dbFile45             WHILE @@FETCH_STATUS = 046             BEGIN47                 SET @tempTSQL = (select CONCAT(‘use [‘, @dbname, ‘] DBCC SHRINKFILE (N‘‘‘, @dbFile, ‘‘‘) with NO_INFOMSGS‘))48                 EXEC sp_executesql @tempTSQL49                 if(@@ERROR = 0)    print(‘        Database file [‘ + @dbFile + ‘] has been shrinked log successfully.‘)50                 FETCH NEXT FROM @dbFilesCursor INTO @dbFile51             END52             CLOSE @dbFilesCursor53             DEALLOCATE @dbFilesCursor54 55             if(@recoveryModel <> ‘SIMPLE‘)56             begin57                 -- Finally changed back58                 SET @tempTSQL = (select CONCAT(‘ALTER DATABASE [‘, @dbname, ‘] SET RECOVERY ‘, @recoveryModel, ‘ with no_wait‘))59                 EXEC sp_executesql @tempTSQL60                 if (@@ERROR = 0)61                 begin62                     print(‘    Database [‘ + @dbname + ‘] recovery model has been changed back to ‘‘‘ + @recoveryModel + ‘‘‘‘)63                 end64                 else 65                 begin66                     print(‘    Database [‘ + @dbname + ‘] recovery model failed to be changed back to ‘‘‘ + @recoveryModel + ‘‘‘‘)67                 end68             end69         end70     end71 FETCH NEXT FROM dbCursor INTO @dbname72 END73 74 CLOSE dbCursor75 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 BIT10 11 OPEN dbCursor12 FETCH NEXT FROM dbCursor INTO @dbname13 14 WHILE @@FETCH_STATUS = 015 BEGIN16     if((@dbname <> ‘master‘) and (@dbname <> ‘model‘) and (@dbname <> ‘msdb‘) and (@dbname <> ‘tempdb‘) and (@dbname <> ‘Resource‘))17     begin18         print(‘‘)19         print(‘Database [‘ + @dbname + ‘] will be shrinked log...‘)20         SET @flag = 121         SET @recoveryModel = (SELECT recovery_model_desc FROM sys.databases WHERE name = @dbname)22         if((@recoveryModel = ‘FULL‘) or (@recoveryModel = ‘BULK_LOGGED‘))23         begin24             SET @tempTSQL = (‘ALTER DATABASE [‘ + @dbname + ‘] SET RECOVERY SIMPLE with no_wait‘)25             EXEC sp_executesql @tempTSQL26             if (@@ERROR = 0)27             begin28                 print(‘    Database [‘ + @dbname + ‘] recovery model has been changed to ‘‘SIMPLE‘‘.‘)29                 SET @flag = 130             end31             else32             begin33                 print(‘Database [‘ + @dbname + ‘] recovery model failed to be changed to ‘‘SIMPLE‘‘.‘)34                 SET @flag = 035             end36         end37 38         if(@flag = 1)39         begin40             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_id43             open @dbFilesCursor44             FETCH NEXT FROM @dbFilesCursor INTO @dbFile45             WHILE @@FETCH_STATUS = 046             BEGIN47                 SET @tempTSQL = (‘use [‘ + @dbname + ‘] DBCC SHRINKFILE (N‘‘‘ + @dbFile + ‘‘‘) with NO_INFOMSGS‘)48                 EXEC sp_executesql @tempTSQL49                 if(@@ERROR = 0)    print(‘        Database file [‘ + @dbFile + ‘] has been shrinked log successfully.‘)50                 FETCH NEXT FROM @dbFilesCursor INTO @dbFile51             END52             CLOSE @dbFilesCursor53             DEALLOCATE @dbFilesCursor54 55             if(@recoveryModel <> ‘SIMPLE‘)56             begin57                 -- Finally changed back58                 SET @tempTSQL = (‘ALTER DATABASE [‘ + @dbname + ‘] SET RECOVERY ‘ + @recoveryModel + ‘ with no_wait‘)59                 EXEC sp_executesql @tempTSQL60                 if (@@ERROR = 0)61                 begin62                     print(‘    Database [‘ + @dbname + ‘] recovery model has been changed back to ‘‘‘ + @recoveryModel + ‘‘‘‘)63                 end64                 else 65                 begin66                     print(‘    Database [‘ + @dbname + ‘] recovery model failed to be changed back to ‘‘‘ + @recoveryModel + ‘‘‘‘)67                 end68             end69         end70     end71 FETCH NEXT FROM dbCursor INTO @dbname72 END73 74 CLOSE dbCursor75 DEALLOCATE dbCursor

給大家帶來的不變深表歉意。

 

[原創文章,轉載請註明出處,僅供學習研究之用,如有錯誤請留言,謝謝支援]

[原網站:http://www.cnblogs.com/lavender000/p/6882741.html,來自永遠薰薰]

DB太大?一鍵幫你收縮所有DB檔案大小(Shrink Files for All Databases in SQL Server)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.