說我要運行以下命令:我可以同時將更新語句應用於多個數據庫嗎?
update users set age = 10
上的數據庫:
db1, db2, db3
所有在同一臺服務器上,我想遍歷並執行相同的操作。
目前我正在通過下拉菜單使用management studio進行手動操作。
希望有更好的辦法。
說我要運行以下命令:我可以同時將更新語句應用於多個數據庫嗎?
update users set age = 10
上的數據庫:
db1, db2, db3
所有在同一臺服務器上,我想遍歷並執行相同的操作。
目前我正在通過下拉菜單使用management studio進行手動操作。
希望有更好的辦法。
不知道這樣做是「動態的」,即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
呵呵,這個想法是有一個循環不知何故,這是重複的腳本,我想避免維護的原因,但謝謝! – codecompleting
指定的服務器作爲中央管理服務器,然後將其他服務器添加到服務器組。然後,您可以在組中的所有數據庫上運行更新。 http://msdn.microsoft.com/en-us/library/bb934126.aspx
這將允許您在多個*服務器*上運行語句,但不能運行多個數據庫。 –
多個服務器=多個數據庫:)授予每臺服務器上的數據庫需要命名相同,但如果它們是那麼這是使用的解決方案。 – Wil
你也許可以用動態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
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,@[email protected] 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
這是我發現有選擇地更新多個數據庫的最佳/最安全的方式。 – capito
您正在使用什麼版本的SQL Server? – Wil
版本2008 R2 – codecompleting
這屬於數據庫管理員SE。 (http://dba.stackexchange.com) – 2011-10-07 01:10:37