I have multiple databases with the same table (an Eventlog with different values). The names of these databases are subject to change. I am trying to display the Eventlog tables in one consolidated table with the corresponding database name.
I tried to using cursor and dynamic SQL statement to achieve this with no luck. As well, I'm not sure if that is the best approach. Would love some help!
-- Create a new table variable to record all the database name
DECLARE @Database_Table table ([TimeStamp] nvarchar(500)
,[EventIDNo] nvarchar(100)
,[EventDesc] nvarchar(1000))
--Create variable for database name and query variable
DECLARE @DB_Name VARCHAR(100) -- database name
DECLARE @query NVARCHAR(1000) -- query variable
--Declare the cursor
DECLARE db_cursor CURSOR FOR
-- Populate the cursor with the selected database name
SELECT name
FROM sys.databases
WHERE name NOT IN ('master','model','msdb','tempdb')
--Open the cursor
OPEN db_cursor
--Moves the cursor to the first point and put that in variable name
FETCH NEXT FROM db_cursor INTO @DB_Name
-- while loop to go through all the DB selected
WHILE @@FETCH_STATUS = 0
BEGIN
SET @query = N'INSERT INTO @Database_Table
SELECT @DB_Name, *
FROM ['+ @DB_Name +'].dbo.EventLog_vw as A'
EXEC (@query)
--Fetch the next record from the cursor
FETCH NEXT FROM db_cursor INTO @DB_Name
END
--Close and deallocate cursor
CLOSE db_cursor
DEALLOCATE db_cursor
SELECT *
FROM @Database_Table