Categories
MSSQL Server

MSSQL Set All Databases to FULL Recovery

This script sets all databases to FULL recovery (except for master, model and tempdb). We can avoid using a cursor by making use of a temporary table. First a temptable gets filled with execution commands, and then the script executes each row until the record id equals the total number of records.

-- Declarations and temptables...
DECLARE @iNumRecs int, @iRecNum int = 1, @vCommand nvarchar(max)
CREATE TABLE #tCommands (ID int IDENTITY(1,1), Command nvarchar(max))

-- Insert Commands into temptable...
INSERT INTO #tCommands (Command)
SELECT N'ALTER DATABASE [' + name + '] SET RECOVERY FULL WITH NO_WAIT' 
FROM [master].[sys].[databases]
WHERE recovery_model_desc = 'SIMPLE' AND name NOT in ('master', 'msdb', 'tempdb')

-- Execute commands from temptable...
SELECT @iNumRecs = COUNT(*) FROM #tCommands
WHILE @iRecNum <= @iNumRecs
BEGIN
 SELECT @vCommand = Command FROM #tCommands
 WHERE ID = @iRecNum
 -- Execute command and increase record number...
 -- EXECUTE(@vCommand) --Alternative, Not preferred...
 EXECUTE sys.sp_executesql @stmt = @vCommand
 SET @iRecNum += 1
END

-- Cleanup...
DROP TABLE #tCommands