четверг, 27 февраля 2020 г.

Сжатие всех баз MSSQL, исключая указанную директорию (папку)

-- Первый фильтр: только для баз с простой моделью восстановления.
-- Второй фильтр: mdf-файл базы не должен находиться в указанной директории.
DECLARE @ExcludeDir NVARCHAR(3000) = 'C:\DATABASES' --directory to exclude
DECLARE @DBPath NVARCHAR(3000) = ''
DECLARE @DBNAME NVARCHAR(150) = ''
DECLARE @EXECSTR NVARCHAR(3000) = ''
SET @ExcludeDir = '%' + UPPER(@ExcludeDir) + '%'
--Drop old table.
USE TEMPDB
IF EXISTS(SELECT [TABLE_NAME] FROM [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_NAME] = 'FSHRINKS')
BEGIN
DROP TABLE FSHRINKS
END
-- Temp table with databases for shrink.
SELECT
IDENTITY(INT, 1,1) AS ID
,DB.*
INTO FSHRINKS
FROM SYS.DATABASES AS DB
WHERE lower(DB.NAME) NOT IN ('master', 'tempdb', 'model', 'msdb')
AND UPPER(DB.state_desc) = 'ONLINE' AND UPPER(DB.recovery_model_desc) = 'SIMPLE'
-- Shrink every database.
DECLARE @X INT = 0
DECLARE @COUNTF INT = (SELECT COUNT(*) FROM FSHRINKS)
WHILE (@X < @COUNTF)
BEGIN
SET @X = @X + 1
SET @DBNAME = (SELECT TOP 1 F.NAME FROM FSHRINKS AS F WHERE F.ID = @X)
-- Getting the path of MDF file
SET @EXECSTR = 'USE [' + @DBNAME + '] '
+ ' SET @DBPath = (SELECT TOP 1 UPPER(DF.physical_name) FROM sys.database_files AS DF WHERE UPPER(DF.type_desc) = ''ROWS'')'
EXEC sp_executesql @EXECSTR, N'@DBPath nvarchar(300) out', @DBPath = @DBPath OUT
USE TEMPDB
PRINT @EXECSTR
PRINT @DBPath
-- Filter by MDF file paths, which not include @ExcludeDir
IF PATINDEX(@ExcludeDir, @DBPath) > 0
BEGIN
CONTINUE
END
-- Shrink
SET @EXECSTR = 'DBCC SHRINKDATABASE(N''' + @DBNAME + ''')'
PRINT @EXECSTR
EXECUTE(@EXECSTR)
END
DROP TABLE FSHRINKS

Комментариев нет:

Отправить комментарий