Tara Kizer Blog

Tara Kizer

DBCC CHECKDB stored procedure

EDIT: This stored procedure has been updated.

Here's a stored procedure that will check the integrity of each of the databases.  I've got it scheduled to run every night on each of our servers.  I recommend putting it into an Admin database (hey just name it Admin!) rather than in master.

CREATE    PROC isp_DBCC_CHECKDB
AS

SET NOCOUNT ON

DECLARE @dbid INT
DECLARE @DBName SYSNAME
DECLARE @SQL NVARCHAR(4000)

SET @dbid = 0

WHILE @dbid < (SELECT MAX(dbid) FROM master.dbo.sysdatabases)
BEGIN

 SELECT TOP 1 @dbid = dbid, @DBName = name
 FROM master.dbo.sysdatabases
 WHERE dbid > @dbid
 ORDER BY dbid

 SET @SQL = 'DBCC CHECKDB(' + @DBName + ')'

 EXEC sp_executesql @statement = @SQL

END

RETURN 0


GO

Legacy Comments


Satish Balusa
2004-06-16
re: DBCC CHECKDB stored procedure
If you want to save few lines of code you can use the following.
sp_MSforeachdb 'DBCC CHECKDB(?)'

Disclaimer : It is an undocumented feature.

Tara
2004-06-17
re: DBCC CHECKDB stored procedure
Yes thanks, I am aware of sp_MSforeachdb.

Lyle Dodge
2004-08-05
re: DBCC CHECKDB stored procedure
Should probably change it to

'DBCC CHECKDB([' + @DBName + '])'

since some people have -,_ in their database names :)

Emma Greenwood
2006-06-14
re: DBCC CHECKDB stored procedure
Is it possible to Exclude Offline databases with this?