While Loop to Iterate through Databases

后端 未结 7 1194
暖寄归人
暖寄归人 2021-02-05 13:05

I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns. this is was I have done

7条回答
  •  被撕碎了的回忆
    2021-02-05 13:48

    My code to search for data from more than one database would be:

    use [master]
    
    go
    
    if object_id('tempdb.dbo.#database') is not null 
    
        drop TABLE #database
    
    go
    
    create TABLE #database(id INT identity primary key, name sysname)
    
    go
    
    set nocount on
    
    insert into #database(name)
    
    select name
    
    from sys.databases
    
    where name like '%tgsdb%' --CHANGE HERE THE FILTERING RULE FOR YOUR DATABASES!
    
    and source_database_id is null
    
    order by name
    
    Select *
    from #database
    
    declare @id INT, @cnt INT, @sql NVARCHAR(max), @currentDb sysname;
    
    select @id = 1, @cnt = max(id)
    from #database
    
    while @id <= @cnt
    
    BEGIN
    
            select @currentDb = name
        from #database
        where id = @id
    
        set @sql = 'select Column1, Column2 from ' + @currentDb + '.dbo.Table1'
        print @sql
        exec (@sql);
        print '--------------------------------------------------------------------------'
        set @id = @id + 1;
    
    END
    
    go
    

提交回复
热议问题