I got some help a while ago from some of you on this board regarding a way to take data from multiple DB's and put into a temp table. Basically we have 35+ DB's, all the same tables and we want to list all the "Users" from each DB into 1 table. This works very well but I am looking to turn this into a Stored Procedure and am getting a few errors and hope you can help again.
Here's the SP:
When I try to save it, I get this error:
Any help would be greatly appreciated!
Here's the SP:
Code:
ALTER PROCEDURE [dbo].[GetAllPOCsInAllDatabases]
AS
IF object_id('tempdb..#Users') IS NOT NULL
DROP TABLE #Users
SELECT 'xxxx' AS DBName, 1 AS TempColumn, *
INTO #Users
FROM MyDB.dbo.Users
WHERE 1=0
UPDATE #Users
SET DBName = null
ALTER TABLE #Users DROP COLUMN UserId
GO
tempdb..sp_rename '#Users.TempColumn','UserId', 'COLUMN'
DECLARE @DBName varchar(20)
DECLARE @sSQL varchar(2000)
DECLARE LoopCursor CURSOR FOR
SELECT 'SC_' + DBName AS 'DBName'
FROM [SCMaster].dbo.Configuration c
WHERE DBName NOT IN ('ABC', '123')
ORDER BY 'SC_' + c.DBName
OPEN LoopCursor
FETCH NEXT FROM LoopCursor
INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sSQL = '
SELECT ''' + @DBName + ''', u.*
FROM [' + @DBName + '].dbo.Users u
INSERT INTO #Users
EXEC(@sSQL)
FETCH NEXT FROM LoopCursor
INTO @DBName
END
CLOSE LoopCursor
DEALLOCATE LoopCursor
SELECT * FROM #Users
Order BY FirstName
GO
When I try to save it, I get this error:
Code:
Msg 15248, Level 11, State 1, Procedure sp_rename, Line 215
Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.
Msg 208, Level 16, State 0, Line 28
Invalid object name '#Users'.
Any help would be greatly appreciated!