Wednesday, July 09, 2008

List recovery model of all databases

I put together a quick SQL query this morning that can be run against an SQL database to retrieve the list of database names and thier recovery models. I only tested against an Microsoft SQL 2005 server but it should work against any SQL server.

The blog will wrap the text incorrectly, of course. when you copy and paste, the commands should work correctly.

USE master
GO

-- Declare a variable to store the value [database name] returned by FETCH.
DECLARE @dbname sysname, @mode varchar(1000)

-- Declare a cursor to iterate through the list of databases
DECLARE db_recovery_cursor CURSOR FOR
SELECT name from sysdatabases

-- Open the cursor
OPEN db_recovery_cursor

-- Perform the first fetch and store the value in a variable.
FETCH NEXT FROM db_recovery_cursor INTO @dbname

-- loop through cursor until no more records fetched
WHILE @@FETCH_STATUS = 0

BEGIN
Set @mode = CONVERT (varchar, DATABASEPROPERTYEX(@dbname,'RECOVERY') )
PRINT 'Database Name: ' + @dbname + ' Recovery Model: ' + @mode

FETCH NEXT FROM db_recovery_cursor INTO @dbname
END

-- close the cursor and deallocate memory used by cursor
CLOSE db_recovery_cursor
DEALLOCATE db_recovery_cursor

No comments: