I have successfully written code to dynamically union the results of a simple select statement across multiple databases. I would like to include the database name itself as a field so that I can identify each record. What is the best way to modify the code below to accomplish that?
My current results look like
field2, field3, field4
b,c,d
2,3,4
I can’t tell what database the row containing (b,c,d) comes from.
And I would like to make sure I see
field1, field2, field3, field4
First_DatabaseName, b,c,d
Second_DatabaseName,2,3,4
And above, I could then see that the row containing (b,c,d) comes from First_Database
DECLARE @sql varchar(max)
SELECT @sql = ISNULL(@sql + 'union all ',' ') + ' SELECT * FROM ' + name + '.dbo.CombinedProvider '
FROM sys.databases
WHERE name in ('First_DatabaseName', 'Second_DatabaseName')
EXEC (@sql)
Just add the name into the subquery that you are using:
By the way, you are using an unsupported technique to do aggregate string concatenation. You might want to learn about “for xml path(”)” as an alternative technique. Check out http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/ for more information than you want to know on this subject.