sp_MSforeachdb iterates through each database in a SQL Server instance. Instead of using a cursor, this Undocumented Stored Procedure is of immense help when I need to run a command against all the databases in my local server. Here are some scenarios where the sp_MSforeachdb can be practically used for your day to day tasks:
- Print all the database names in a SQL Server Instance
- Print all the tables in all the databases of a SQL Server Instance
- The example shown above prints the tables for master, model, msdb and tempdb. If you want to eliminate these databases in the query use, do the following:
- Display the size of all databases in a SQL Server instance
- Determine all the physical names and attributes(size,growth,usage) of all databases in a SQL Server instance
- Change Owner of all databases to 'sa'
- Check the Logical and Physical integrity of all objects in the database
EXEC sp_MSforeachdb 'USE ?; PRINT DB_NAME()'
EXEC sp_MSforeachdb 'USE ? SELECT DB_NAME() + ''.'' + OBJECT_NAME(object_Id) FROM sys.tables'
EXEC sp_MSforeachdb '
USE ?
SELECT OBJECT_NAME(object_Id)
FROM sys.tables
where DB_NAME() NOT IN(''master'', ''model'', ''msdb'', ''tempdb'')
'
EXEC sp_MSforeachdb 'USE ?; EXEC sp_spaceused'
EXEC sp_MSforeachdb 'USE ? EXEC sp_helpfile;'
EXEC sp_MSforeachdb 'USE ?; EXEC sp_changedbowner ''sa'''
sp_MSforeachdb 'DBCC CHECKDB(?)'
Similarly you can backup all databases at one go or do a CHECKSUM using this useful procedure. There are many more ways to use it. Got a useful tip on sp_MSforeachdb? Share it using the comments below.
This entry was posted
on Wednesday, September 15, 2010
and is filed under
SQL Server,
Tools
.
You can leave a response
and follow any responses to this entry through the
Subscribe to:
Post Comments (Atom)
.
0 comments