Skip to main content

Cloud

For Each DB

One of my favorite SQL stored procedures has been hiding in the master database since SQL 7. It’s a useful utility for running commands against every database on a given SQL Server named sp_MSForeachDB. It undocumented and may have been created for running updates during SQL upgrades. But we can put it to work for creating reports and other repetitive tasks.

Here’s the syntax:
EXEC sp_MSforeachdb @command1, @replacechar, @command2, @command3, @precommand, @postcommand

Parameter Desc
@command1 nvarchar(2000) field specifying the first command to run against each database. May not be blank.
@replacechar nchar(1) field specifying the character in the command parameters to replace with the database name. Defaults to ?
@command2 nvarchar(2000) field specifying the 2nd command to run against each database
@command3 nvarchar(2000) field specifying the 3rd command to run against each database
@precommand nvarchar(2000) field specifying a command to be run prior any commands against any database
@postcommand nvarchar(2000) field specifying a command to be run after running all commands

–Example to print the names of all the databases on the server:

EXEC [sp_MSforeachdb] ‘PRINT ”Database: ?”’
Results:
Database: DKADatabase
Database: master
Database: model
Database: msdb
Database: Northwind


–Example to get all the open transactions for every database on the server:

DECLARE @command1 nvarchar(2000)
DECLARE @replacechar nchar(1)
DECLARE @command2 nvarchar(2000)
DECLARE @command3 nvarchar(2000)
DECLARE @precommand nvarchar(2000)
DECLARE @postcommand nvarchar(2000)

— Set parameter values
SET @replacechar = ‘?’
SET @precommand = ‘PRINT ”Server: ” + @@SERVERNAME’
SET @command1 = ‘USE ? PRINT ”Database: ?”’
SET @command2 = ‘DBCC OPENTRAN(?) WITH NO_INFOMSGS PRINT” ” ‘
SET @command3 = ”
SET @postcommand = ‘SELECT GETDATE() AS [Completed]’
EXEC [sp_MSforeachdb] @command1, @replacechar, @command2, @command3, @precommand, @postcommand

Results:
Server: DEV
Database: DKADatabase
No active open transactions.

Database: master
No active open transactions.

Database: model
No active open transactions.

Database: msdb
No active open transactions.

Database: Northwind
No active open transactions.

Completed
——————————————————
2006-04-02 17:05:37.527

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Aaron Steele

More from this Author

Follow Us