Loop through databases on server, and update data

孤街醉人 提交于 2019-12-12 10:40:16

问题


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?


回答1:


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)



回答2:


EXEC sp_MSForEachDB ' Use ?; UPDATE ?.dbo.MyTable SET MyValue=999  '



回答3:


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

EXEC sp_msforeachdb 'PRINT ''?'''

The ? is the database name.



来源:https://stackoverflow.com/questions/3206304/loop-through-databases-on-server-and-update-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!