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:

http://ritesh-a-shah.blogspot.com/2009/03/spmsforeachtable-undocumented-but.html

http://ritesh-a-shah.blogspot.com/2009/03/empty-all-table-or-delete-all-data-from.html

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: