Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...