Undocumented Stored Procedure sp_MSforeachdb

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.

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.

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.

Artemakis Artemiou
Artemakis Artemiou is a Senior SQL Server Architect, Author, and a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 15 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and TechHowTos.com. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Artemakis's official website can be found atย aartemiou.com.