grady grady - 1 month ago 15
SQL Question

Run script on multiple DBs (SQL Server)?

Let's say I have some update script:

update sometable set somecolumn = 'somevalue' where xyz = 0


Now let's say I have multiple databases, like DB1, DB2, DB3 and so on. How could I run this script on all of them without doing it manually?

Thanks :)

Answer

If you wanted all databases, you can use sp_MSforeachdb:

http://www.databasejournal.com/features/mssql/article.php/3441031/SQL-Server-Undocumented-Stored-Procedures-spMSforeachtable-and-spMSforeachdb.htm

EXEC sp_MSforeachdb @command1="UPDATE ?..sometable SET somecolumn='somevalue' WHERE xyz=0"

Or for specific databases, you could try some of the logic as seen here:

http://www.sqlservercurry.com/2009/04/6-common-uses-of-undocumented-stored.html

Hope that helps.