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 '?'",
@command2="ALTER DATABASE [?] SET COMPATIBILITY_LEVEL = 100";
*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.
Labels: SQL Server, Undocumented