Skip to content
Advertisement

Displaying multiple database tables in one table

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

Advertisement

Answer

If you need a single resultset and all tables have the same layout, this should work:

DECLARE @sql nvarchar(4000) =
    (SELECT STRING_AGG(CONCAT(
        'SELECT ''',
        QUOTENAME(name),
        ''',
        * FROM ',
        QUOTENAME(name),
        '..Table ',
        CHAR(10)
        ), ' UNION ALL ' + CHAR(10))
    FROM sys.databases);

SELECT @sql;  -- for checking
EXEC(@sql);

If you’re on compatibility level 130 or lower, you will have to use XML PATH(TYPE, '') to aggregate. I will leave that to you.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement