I have 9 databases in my SQL Server setup. Let's call them ONE_DB, TWO_DB etc. A quite common task I find myself doing is extracting some data from all nine instances (usually quite small tables like config etc) with the same query for the same table but over all databases. I would love a union all select interesting_col from *.dbo.tableX
I have come up with one way to do this, based on other questions here on SO, but I am not quite content with this solution. Lets say I only want one column from one table, I first run the SQL query below...
declare @db varchar(30)
declare @db_list varchar(200)
set @db = ''
set @db_list = 'ONE_DB,TWO_DB,THREE_DB,FOUR_DB,FIVE_DB,SIX_DB,SEVEN_DB,EIGHT_DB,NINE_DB'
while len(@db_list) > 0
begin
set @db = left(@db_list, charindex(',', @db_list+',')-1);
set @db_list = stuff(@db_list, 1, charindex(',', @db_list+','), '');
exec ( 'use '+@db+'; select tx.interesting_columns from dbo.TableX as tx;')
end
... and then i copy-paste the 9 result sets to Excel manually. Of course I normally do some more processing in the select statement such as different joins, aggregations, case-clauses etc. but I guess you get the point.
This process is quite okay, but the code is not very easy to read when there are more complex select statements. It is also quite difficult for a new person to read this code as the syntax highlighter interprets all the interesting stuff (the select statement) as a string.
What is the "good" way to deal with this?