I have a server with multiple databases. I need to loop through these databases and change a value in one record, in one table, in each database. How can this be done?
+3
A:
You could 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)
Andomar
2010-07-08 17:32:26
Thanks Andomar. I think this is more suited to my situation than the 'sp_MSForEachDB' stored procedure as I may need to be more custom with each database. Using this method I could create a loop, and various IF conditions to get the results I require. Thanks.
Curt
2010-07-09 08:41:58
+1
A:
There is an undocumented stored procedure sp_MSForEachDB which will execute SQL for each database.
EXEC sp_msforeachdb 'PRINT ''?'''
The ? is the database name.
Chris Diver
2010-07-08 17:34:39
+3
A:
EXEC sp_MSForEachDB ' Use ?; UPDATE ?.dbo.MyTable SET MyValue=999 '
rlb.usa
2010-07-08 17:35:33