通过所有数据库

时间:2015-06-04 18:05:01

标签: sql sql-server

我需要第二个查询来运行第一个结果。第一个查询为我提供了第二个查询所需的所有databaseNames

SELECT name 
FROM sys.databases where name like '%MySomething%'

和 第二个查询:

Update [databaseName].[someschema].[mytableSomething]
Set Flag = 1
Where Name = 'MyCondition'

所以基本上我需要在它存在的所有数据库中更新特定表中的列。

1 个答案:

答案 0 :(得分:1)

使用First Select Query创建临时表,并使用While循环遍历每个数据库名称,并使用在循环中使用每个数据库名称更新查询。

Psuedo代码将是这样的

SELECT name INTO #temprecords
FROM sys.databases where name like '%MySomething%'

然后使用While循环

counter = 1
   While loop for each record in temp table until counter <= total record in temp table
    Begin
         Get Database name in for counter 1
         Update query with each database name
       counter ++
     END

修改: - 你的代码将是这样的

Declare @Count int, @Ini  int       
SELECT name,ROW_NUMBER() Over(Order BY database_id) as RowID
    INTO #temprecords
FROM sys.databases --where name like '%MySomething%'

SET @Count = (Select Count(*) from #temprecords)
SET @Ini = 1
While @Ini <= @Count
BEGIN
   Declare @dbname varchar(max),@qry varchar(max)
   SET @dbname = (Select name From #temprecords Where RowID = @Ini)

   SET @qry = 'Update '+ @dbname +'.[someschema].[mytableSomething]
   Set Flag = 1
   Where Name = MyCondition'

   --EXEC(@qry) --- uncomment this line one you check that @qry has correct query to update
   SET @Ini = @Ini + 1
END