Looping through databases on the server and updating data

I have a server with several databases. I need to go through these databases and change the value in one record in one table in each database. How can I do that?

+5
source share
3 answers

You can use dynamic SQL:

declare @query varchar(max)
set @query = ''

select  @query = @query + 'UPDATE ' + name + 
            '.dbo.YourTable set value = 1 where id = 2; '
from    master.sys.databases
where   name <> 'master'

exec (@query)
+8
source
EXEC sp_MSForEachDB ' Use ?; UPDATE ?.dbo.MyTable SET MyValue=999  '
+11
source

There is an undocumented stored procedure sp_MSForEachDB that will execute SQL for each database.

EXEC sp_msforeachdb 'PRINT ''?'''

What? This is the name of the database.

+3
source

All Articles