I've got some SQL that I'm trying to create and need some help. I have many (35+) DB's that are identical in nature but hold different content. I am trying to create a SQL statement that will go through each DB and select the contents from the 'Users' table and put them in a temp table. Then, once it's done, select the contents of that temp table. Here's what I've got so far:
The Messages window shows all the rows being affected but at the end it states this error:
I'm assuming it's because the table is no longer available in memory....but how can I accomplish this?
BTW, the first SELECT statement is selecting all my DB's that I have stored in a table.
Code:
DECLARE @DBName varchar(20)
DECLARE @s varchar(2000)
DECLARE LoopCursor CURSOR FOR
SELECT 'SC_' + DBName AS 'DBName' FROM [SCMaster].dbo.Configuration c
WHERE DBName NOT IN ('TIER1', 'FAAO')
ORDER BY 'SC_' + c.DBName
OPEN LoopCursor
FETCH NEXT FROM LoopCursor
INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @s = '
SELECT *
INTO #TempTable
FROM ' + @DBName + '.dbo.Users'
exec(@s)
FETCH NEXT FROM LoopCursor
INTO @DBName
END
CLOSE LoopCursor
DEALLOCATE LoopCursor
GO
Select * from #TempTable
The Messages window shows all the rows being affected but at the end it states this error:
Code:
Server: Msg 208, Level 16, State 1, Line 2
Invalid object name '#TempTable'.
I'm assuming it's because the table is no longer available in memory....but how can I accomplish this?
BTW, the first SELECT statement is selecting all my DB's that I have stored in a table.