Sp_MsForEachDB undocumented stored procedure in SQL Server 2005:

Sp_MsForEachDB is an un-documented stored procedure by Microsoft. It is useful when you want to perform same action in all databases in one SQL Server instance. Without Sp_MsForEachDB you have to go for cursor and you know that cursor is resource consuming and reduce the speed.

I have written article about another undocumented stored procedure named “Sp_MsForEachTable” which is for performing same action for all tables in one database. You can refer that article at:



Anyway, let us see how we can use Sp_MsForEachDB practically.

–this script will return all the table of all databases in sql server instance

–along with db name and schema

exec sp_MSforeachdb

‘USE ?

select ob.name,sch.name,”?” AS ”DATABASE” from ?.sys.tables ob

inner join ?.sys.schemas as sch on sch.schema_id = ob.schema_id’

This was just an example of Sp_MsForEachDB. You can use it more efficiently in your customize need like granting permission to user in every database, change some property of all databases available in instance of SQL Server etc.

Practical example of this article is created by Rashmika Vaghela (good SQL developer and my subordinate). She was inspired to write something by regularly reading my blog and asked me to contribute in any of my article. I was planning to write article about Sp_MsForEachDB so I told her to make one practical example for Sp_MsForEachDB.

Thank you Rashmika.

Reference: Ritesh Shah

Microsoft SQL Server Blog. Fight the fear of SQL with SQLHub.com. Founder is Ritesh Shah

Author: Riteshshah

Ritesh Shah is a database professional with having 16+ years of experience in various domain of IT field. He is a author of many technical articles on Microsoft Technology and authored a book of SQL Server 2012 Performance Tuning cookbook. He loves work with different Microsoft Products.