Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder ofhttp://www.SQLHub.com
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
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
Empty all table or delete all data from all table by sp_MSforeachtable in SQL-SERVER 2005
Now let us see, how we can do empty the tables.
sp_MSforeachtable: Undocumented but useful stored procedure for auto iteration in SQL-Server 2005.