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
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.