While Loop to Iterate through Databases

后端 未结 7 1189
暖寄归人
暖寄归人 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:41

    DECLARE @Loop int
    DECLARE @MaxLoop int
    DECLARE @DBName varchar(300)
    DECLARE @SQL varchar(max)
    
    SET @Loop = 1
    SET @DBName = ''
    
    set nocount on
    SET @MaxLoop =  (select count([name]) FROM sys.databases where [name] like 'Z%')
    WHILE @Loop <= @MaxLoop
        BEGIN
            SET @DBName = (select TableWithRowsNumbers.name from (select ROW_NUMBER() OVER (ORDER by [name]) as Row,[name] FROM sys.databases where [name] like 'Z%' ) TableWithRowsNumbers where Row = @Loop)
            SET @SQL = 'USE [' + @DBName + ']'
            exec (@SQL)
            ...
            ...
            set @Loop = @Loop + 1
        END
    

    ***Note: I didn't add the check if exists here.

提交回复
热议问题