For Each Database
Today I was writing a script that would go through all the databases on a server and add a user as a member of readonly and denywriter. It’s a script that I’ll probably need again, and so I discovered the “EXEC sp_MSForEachDB” stored procedure. This undocumented and clearly powerful sproc needs to be respected, however it’s certainly useful for batching a lot of commands quickly.
sql execute master.sys.sp_msforeachdb 'select ''?'' '
You can also specify particular databases, so you can ignore system databases, or specify particular databases and execute a command against a subset of databases
EXEC sp_MSForEachDB 'IF ''?'' IN (''Contoso'',''AdventureWorks2012'')
select ''?'' '