Pages

Search This Blog

Monday, August 16, 2010

[T-SQL] Shrink log in all your user databases

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = COALESCE(@SQL + CHAR(13) + CHAR(10),'') + N'
Use ' + QUOTENAME(d.[name]) + ';' + CHAR(13) + '
ALTER DATABASE ' + QUOTENAME(d.[name]) + ' SET RECOVERY SIMPLE;
DBCC SHRINKFILE (' + QUOTENAME(mf.[name],'''') + ', 1);
ALTER DATABASE ' + QUOTENAME(d.[name]) + ' SET RECOVERY FULL;'
FROM sys.databases d
INNER JOIN sys.master_files mf ON [d].[database_id] = [mf].[database_id]
WHERE
d.[database_id] > 4 --no sys dbs
AND d.recovery_model = 1
AND d.is_read_only = 0
AND mf.[type] = 1 --log files
ORDER BY d.name

--print @SQL

EXECUTE (@SQL)

No comments: