Don't panic!

 
 

Cry How to...

Run dbcc checkdb on each database (using cursors)


The simplest way to run 'dbcc checkdb' (to check the structural integrity of an SQL Server database) on each database in the system is to write a simple script that includes each database by name, for example:

dbcc checkdb('MASTER') with no_infomsgs
dbcc checkdb('MODEL') with no_infomsgs
.
.
dbcc checkdb('TEMP') with no_infomsgs

The disadvantage of this approach is that the script needs to be updated each time a new database is added or a database deleted. It is also unlikely to be portable from one server to another without being rewritten.

An alternate and more adaptable approach is to let the script determine what databases are present and to run dbcc checkdb on each in turn:

declare database_cursor CURSOR for select name from master..sysdatabases
declare @database_name sysname

open database_cursor
fetch next from database_cursor into @database_name
while @@FETCH_STATUS=0
begin
  print @database_name
  dbcc checkdb(@database_name) with no_infomsgs
  fetch next from database_cursor into @database_name
end

close database_cursor
deallocate database_cursor

The advantage of this approach is that the script does not need updating should a new database be added or one removed and it can be copied from one server to another and executed without change.


These notes have been tested against SQL Server 7, SQL Server 2000 and SQL Server 2005.