Introduction
In this article, I describe the Sp_msforeachdb System Stored Procedure in SQL Server 2012. Sp_msforeachdb allows us to execute a T-SQL statement against every database in the current SQL Server instance. In this article, I describe the Sp_msforeachdb Stored Procedure, the use of it and how to make a backup of all the databases using the Sp_msforeachdb Stored Procedure.
In my previous article, I described the use of Sp_msforeachtable; you can visit: Sp_msforeachtable in SQL Server 2012
Sp_msforeachdb Stored Procedure
It is an undocumented Stored Procedure that allows you to iterate through all the databases in a SQL Server instance. sp_MSforeachdb will execute a T-SQL statement against every database associated with the current SQL Server instance.
The SP "sp_MSforeachdb" is found in the "master" database and especially useful when you're performing database administration and maintenance tasks, such as backup operations.
Syntax
- declare @cmd1 varchar(500)
- declare @cmd2 varchar(500)
- declare @cmd3 varchar(500)
- set @cmd1 ='your 1st command'
- set @cmd2 ='your 2nd command'
- set @cmd3 ='your 3rd command'
- exec sp_MSforeachdb @command1=@cmd1,
- @command2=@cmd2,
- @command3=@cmd3
Showing all the databases
- declare @cmd varchar(500)
- set @cmd='select ''?'''
- exec sp_MSforeachdb @cmd
Print the name of all databases
- declare @cmd varchar(500)
- set @cmd='USE ? PRINT DB_NAME()'
- EXECUTE sp_msforeachdb @cmd

Awanish KumarPosted Jan 13, 2016, 4:01 AM
good explaination
Deepak MiddhaPosted Jan 7, 2013, 5:04 AM
Thanx Manish
Manish SharmaPosted Jan 7, 2013, 1:21 AM
Nice explanation Deepak