SQL SERVER: Shrink Log File of all databases in one script

--

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 CURSOR
SET @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
END
CLOSE @getid
DEALLOCATE @getid

Thank for reading 😊

ELMASLOUHY Mouaad,

--

--

ELMASLOUHY Mouaad

Computer science Engineer Student, A lover of everything that urges the mind to work hard such as Quantum Physics, General Medicine, Personal dev…