среда, 19 февраля 2020 г.

Сжатие (обрезка) журналов транзакций всех баз MSSQL


Скрипт предназначен для баз с простой моделью восстановления (модель Simple).
DECLARE @RemainSize NVARCHAR(10) = '0' -- size (Mb) to be remain
DECLARE @DBNAME NVARCHAR(150) = ''
DECLARE @LOGNAME 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 for every file.
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 = 'USE [' + @DBNAME + '] '
+ 'DECLARE @LOGNAME NVARCHAR(150) '
+ 'SELECT @LOGNAME = DF.NAME FROM SYS.database_files AS DF WHERE DF.TYPE = 1 PRINT @LOGNAME '
+ 'DBCC SHRINKFILE (@LOGNAME , ' + @RemainSize + ', TRUNCATEONLY) '
PRINT @EXECSTR
EXECUTE(@EXECSTR)
END
DROP TABLE FSHRINKS

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

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