SQL SERVER: Shrink Log File of all databases in one script
Mar 22, 2022
The script will create a SQL command from a select of sys.master_files and then will create a cursor for that to execute each SQL command alone after.
The script is written in Transact SQL, and this is the Format of the script :
This is the code :
DECLARE @sqlcommand NVARCHAR(500)
DECLARE @getid CURSORSET @getid = CURSOR FOR
SELECT
'USE [' + d.name + N']; ALTER DATABASE [' + d.name + N'] SET RECOVERY SIMPLE; DBCC SHRINKFILE (' + mf.name + ' , 1, TRUNCATEONLY);'
FROM
sys.master_files mf
JOIN sys.databases d
ON mf.database_id = d.database_id
WHERE mf.type_desc = 'LOG' AND d.name not in ('master','model','tempdb','msdb');OPEN @getid
FETCH NEXT
FROM @getid INTO @sqlcommand
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC(@sqlcommand)
FETCH NEXT
FROM @getid INTO @sqlcommand
ENDCLOSE @getid
DEALLOCATE @getid
Thank for reading 😊
ELMASLOUHY Mouaad,