Shrink transaction log files for all databases in SQL Server
Shrink transaction log files for all databases in SQL Server
USE master;
/* Note **If a datatabase has more than one transaction log file,each will have this target size.*/DECLARE@target_size_mb NVARCHAR(20) =100;
DECLARE@SQL NVARCHAR(4000);
SET@SQL='USE [?]DECLARE @Updateability NVARCHAR(100)SET @Updateability = CAST(DATABASEPROPERTYEX(''?'', ''Updateability'') AS NVARCHAR(100))IF @Updateability = ''READ_WRITE ''BEGIN RAISERROR(''INFO: Shrinking transaction log of database: %s'', 10, 1, ''?'') -- open a cursor so we can iterate through and shrink all log files RAISERROR(''INFO: Truncate all transaction log files.....'', 10, 1) WITH NOWAIT; DECLARE @log_file_name sysname; DECLARE c1 cursor for SELECT name from sys.database_files where type=1; OPEN c1; FETCH c1 into @log_file_name; WHILE @@FETCH_STATUS = 0 BEGIN RAISERROR(''INFO: Truncating transaction log file %s....'', 10, 1, @log_file_name) WITH NOWAIT; DBCC SHRINKFILE (@log_file_name, '+@target_size_mb +'); FETCH c1 into @log_file_name; END CLOSE c1; DEALLOCATE c1; PRINT ''''ENDELSE RAISERROR(''Skipping "database" %s in Updateability mode "%s"'', 10, 1, ''?'', @Updateability) '
PRINT @SQLexec sp_MSforeachdb @SQL;