我可以同时将更新语句应用于多个数据库吗?

时间:2011-10-06 16:54:13

标签: sql-server

说我想运行以下内容:

update users set age = 10

在数据库上:

db1, db2, db3

所有在同一台服务器上,我想循环并执行相同的操作。

目前我通过下拉列表使用管理工作室手动执行此操作。

希望有更好的方法。

4 个答案:

答案 0 :(得分:1)

不确定是否“动态”执行此操作,即服务器中所有数据库上的FOR-EACH样式循环,但这应该有效:

USE db1
    update users set age = 10
GO
USE db2
   update users set age = 10
GO
USE db3
    update users set age = 10

答案 1 :(得分:1)

你可以用动态SQL做到这一点。像这样:

create table #dbs (db_name sysname not null)
insert into #dbs values ('db1'),('db2'),('db3')

declare curs cursor for
select db_name from #dbs
declare @db sysname, @sql nvarchar(max)
open curs

while(1=1)
begin
   fetch next from curs into @db
   if (@@fetch_status <> 0)
      break
   set @sql = 'update ' + quotename(@db) + '.dbo.users set age = 10'
   exec(@sql)
end
close curs
deallocate curs
drop table #dbs

答案 2 :(得分:0)

将服务器指定为中央管理服务器,然后将其他服务器添加到服务器组。然后,您可以在组中的所有数据库上运行更新。 http://msdn.microsoft.com/en-us/library/bb934126.aspx

答案 3 :(得分:0)

use [WWAUTHxxx__]  -- a db containing active databases.
set nocount on
declare @Catalog as nvarchar(32)
declare @LibraryName as varchar(255)
declare @dbtable as varchar(50)
declare @retval as nvarchar(50)
declare @sSQL as nvarchar(max)
declare @parmdef as nvarchar(500)
declare @retvalout as nvarchar(50)
Declare Library_Cursor Cursor for
   select  top(1000)    xCatalog, xLibraryName
          from Active_DBs  
order by xcatalog
    Open Library_Cursor;
Fetch Next from Library_Cursor  into @Catalog, @LibraryName
   while @@Fetch_status = 0
       begin
         set @dbTable = @Catalog + '.dbo.las_circperiods' 
         set @ParmDef = N'@retvalOUT int OUTPUT';
         set @sSQL = N'Select @retvalout =  count(*) from ' + @dbtable
              + ' where xlastcircdate is null'
        exec sp_executesql @ssql,@parmdef,@retvalout=@retval output


     if @retval > 0  -- check/print Sql and then activate.
                     -- I like checking to see the potentially affected databases.
           begin 
              print @Catalog   + ',' +  @LibraryName + ',' + @retval 
              set @ssql = N'update ' + @dbTable 
                + ' set xlastcircdate = ''''  '
                + ' where xlastcircdate is null'

        --  print @ssql  -- View what you might will do
       exec sp_executesql @ssql    -- Do it.
            end

         Fetch Next from Library_Cursor  into @Catalog, @LibraryName
       end;
     close Library_cursor
     Deallocate Library_cursor