воскресенье, 23 февраля 2020 г.

Сжатие всех баз MSSQL


Добавлен фильтр: только для баз с простой моделью восстановления.
DECLARE @DBNAME NVARCHAR(150) = ''
DECLARE @EXECSTR NVARCHAR(3000) = ''
--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)
SET @EXECSTR = 'DBCC SHRINKDATABASE(N''' + @DBNAME + ''')'
PRINT @EXECSTR
EXECUTE(@EXECSTR)
END
DROP TABLE FSHRINKS

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

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