I have about 40 different databases and they have the same exact table and column structure. How can I retrieve all of them at once using the same select statement?
For example:
USE [Database1]
GO
SELECT a.Column1, b.Column3,
FROM table1 a
JOIN table2 b
ON a.key1 = b.key1
The above query will only give me the result set for 1 database only. I can get the different result set from the different database by changing the USE header but what I am trying to do is to run my select statement and get all the result set from all 40 databases?
This error comes if the table does not exist
In the database
Maybe it's looking at system databases
Master
model
tempdb
Reportdb
To avoid it
Try
EXEC master..sp_MSForeachdb '
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
SELECT ''?''
Select statement here
END
Yes, you are correct, I wasn't clear when I put the ellipsis (...) in the query, I meant to say you continue that pattern for the remaining 37 databases, with UNION ALL between each SELECT.
Another way is to generate the script and copy paste it
in New SQL Query window and run it
Script generation -- Script
script to generate script
SELECT 'use ' + NAME + ' go'
+ ' SELECT a.Column1, b.Column3, FROM table1 a JOIN table2 b ON a.key1 = b.key1 go'
FROM sys.databases
WHERE NAME NOT IN ( 'master', 'tempdb', 'model', 'msdb' )
IF OBJECT_ID('tempdb.dbo.#results') IS NOT NULL
DROP TABLE #results;
SELECT TOP (0) DB_NAME() AS db_name, column1, column3, GETDATE() AS when_run
INTO #results
FROM dbo.table1 a
INNER JOIN dbo.table2 b
EXEC dbo.sp_MSforeachdb '
IF ''?'' NOT IN (''Database1'',''...your_list_of_db_names_here...'')
RETURN;
USE [?];
PRINT ''?'';
INSERT INTO #results
SELECT ''?'', a.Column1, b.Column3, GETDATE()
FROM dbo.table1 a
INNER JOIN dbo.table2 b
ON a.key1 = b.key1
'
SELECT *
FROM #results
ORDER BY db_name