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.

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

sql EXEC sp_MSForEachDB ‘IF “?” IN (“Contoso”,“AdventureWorks2012”) select “?” ‘ ```

2014-03-21-15_53_01_png