SQL Server Central is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

SP_MSFOREACHDB - Getting a list of databases via TSQL.

By Brian Knight, 2001/05/31

Total article views: 9632 | Views in the last 30 days: 191
Cursors provide a powerful tool for DBAs but sometimes they're not needed. The procedure sp_MSforeachdb with the @command1 through @command3 parameter and is very similary to sp_Foreachtable. Sp_MSforeachdb gives a DBA the ability to cycle through every database in your catalog. Although, the procedure was introduced in SQL Server 6+, Microsoft has made major improvements in SQL Server 7.0 and 2000. The procedure is especially useful if you'd like to run through a list of databases for standard DBCCs.

In SQL Server 7.0 and 2000, you can run a DBCC CHECKDB on all databases by using the following :

EXEC sp_Msforeachdb "DBCC checkdb ('?')"

In SQL 6.5 however, you must create a temporary table and in the same session, run a procedure to populate the table. After that, you have the same capabilities as in 7.0 and 2000, as long as you stay in the same connection. To run sp_MSforeachdb in SQL 6.5, you must run the following:


Create table #SQLOLEDbUserProfile
(dbid int NOT NULL PRIMARY KEY,
profilebits int NOT NULL)
go

sp_MSdbuserprofile 'init'
go

--insert your desired code here (I'm just doing maintenance)
EXEC sp_Msforeachdb "DBCC checkdb ('?')"

As you can see, I'm just performing a DBCC CHECKDB with sp_MSforeachdb. You can also use this procedure for sizing, and placing databases in single user mode. If you have any other ideas for applications, please feel free to contribute them to the DBA to DBA section.

By Brian Knight, 2001/05/31

Total article views: 9632 | Views in the last 30 days: 191
Your response
 
 
Related tags
 
Like this? Try these...

Introducing IQReference

By Steve Jones | Category: Product Reviews
(not yet rated) | 3,110 reads
Already registered?  

Free registration required

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Register

E-mail address:
Password:
Password (confirm):

  

Subscriptions

We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.

Steve Jones
Editor, SQLServerCentral.com