Undocumented Stored Procedure sp_MSforeachdb

A really neat undocumented SQL Server stored procedure is sp_MSforeachdb.
This stored procedure takes as parameters SQL commands which are then executed against all databases on the current SQL Server instance.


Simple Example of sp_MSforeachdb in SQL Server

A simple example (“Hello World”-style 🙂 is the following which lists all the databases in the current SQL Server instance:

exec sp_MSforeachdb
@command1="print '?'";

The stored procedure upon its execution replaces the question mark (?) with each database’s name.


Other Examples of sp_MSforeachdb

You can of course build more complex syntaxes like in the case where you just performed a side-by-side DBMS migration to SQL Server 2008 and you want to set the compatibility level for all the databases to 100 (SQL Server 2008) after of course you ensured that the databases are fully compatible with this version of SQL Server:

exec sp_MSforeachdb
@command1="print '?'",


*Note: Even though the stored procedure sp_MSforeachdb enables you to execute SQL commands against all the databases in a SQL Server instance, you must be extremely careful with the commands which you compose as this stored procedure access all the databases including the SQL Server system databases as well.

Also, I would not recommend putting something into a Production environment using the SQL Server undocumented stored procedures as one of the reasons for which they are undocumented, is that they might be removed at any time, as an example like in the case of a new SQL Server Service Pack or a new release.

Strengthen your SQL Server Administration Skills – Enroll to our Online Course!

Check our online course on Udemy titled “Essential SQL Server Administration Tips
(special limited-time discount included in link).

Via the course, you will learn essential hands-on SQL Server Administration tips on SQL Server maintenance, security, performance, integration, error handling and more. Many live demonstrations and downloadable resources included!

Essential SQL Server Administration Tips - Online Course with Live Demonstrations and Hands-on Guides
(Lifetime Access/ Live Demos / Downloadable Resources and more!)

Enroll from $12.99

Featured Online Courses:


Read Also:


Subscribe to our newsletter and stay up to date!

Subscribe to our YouTube channel (SQLNetHubTV)!

Like our Facebook Page!

Check our SQL Server Administration articles.

Check out our latest software releases!

Check our eBooks!


Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)


Reference: SQLNetHub.com (https://www.sqlnethub.com)

© SQLNetHub