This stored procedure is very powerfull command.
It replace the using of curores and make it easy to maintainance the Server DBs with very short and readable command.
The syntex and the parameters are:
Exec sp_MSforeachDB
@command1, --first command to perform
@replacechar, --Command character to be replaced with databases name at run-time. default is "?"
@command2, --second command to perform (Optional)
@command3, --Third command to perform (Optional)
@whereand, --Filter for objects we do not want to include at run-time
@precommand, --Optional command you to run once before running the loop on all databases
@postcommand --Optional command you to run once after running the loop on all databases
In the next example, you can add your execution code to be run on all DBs except for system DBs and specific DBs.
SECLARE @command varchar(max) SELECT @command = 'USE ?
print DB_Name()
begin try
IF DB_ID()>4 and DB_Name() not in (''SampleDB1'',''SampleDB2'')
begin
--Write here. All required operations
end
end try
begin catch
select error_message()
end catch
'
print @command
EXEC sp_MSforeachdb @command