Loop through databases on server, and update data
I ha开发者_JS百科ve 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?
EXEC sp_MSForEachDB ' Use ?; UPDATE ?.dbo.MyTable SET MyValue=999 '
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)
There is an undocumented stored procedure sp_MSForEachDB which will execute SQL for each database.
EXEC sp_msforeachdb 'PRINT ''?'''
The ? is the database name.
精彩评论