Executing SQL query on multiple databases

前端 未结 7 1575
无人共我
无人共我 2021-01-02 19:25

I know my post has a very similar title to other ones in this forum, but I really couldn\'t find the answer I need.

Here is my problem, I have a SQL Server running o

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 19:48

    You can use the following script to run the same script on a set of databases. Just change the filter in the insert line.

    
    declare @dbs table (
      dbName varchar(100),
      done bit default 0
    )
    
    insert @dbs select [name], 0 FROM master.dbo.sysdatabases WHERE [Name] like 'targets_%'
    
    while (exists(select 1 from @dbs where done = 0))
    begin
      declare @db varchar(100);
      select top 1 @db = dbName from @dbs where done = 0;
      exec ('
        use [' + @db + '];
        update table1 set
          col1 = '''',
          col2 = 1
        where id = ''45b6facb-510d-422f-a48c-687449f08821''
      ');
      print @db + ' updated!';
      update @dbs set done = 1 where dbName = @db;
    end
    
    

    If your SQL Server version does not support table variables, just use Temp Tables but don`t forget to drop them at the end of the script.

提交回复
热议问题