using samples I found in this site, I succedeed to write the following query. It works well, however, I would like to get the name of each database being queried be reported in the results, next to those 2 columns. All my attempts have failed. Any help, please.
DECLARE @sql varchar(max);
SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') + 'SELECT column1, column2 FROM ' + QuoteName(name) + '.dbo.T_MyTable'
FROM sys.databases WHERE database_id > 4 AND state = 0
;
PRINT @sql
EXEC (@sql);
as an example, the following fails with an Invalid column name error
DECLARE @sql varchar(max);
SELECT @sql = Coalesce(@sql + ' UNION ALL ', '') + 'SELECT SoStoreNameTx, SoStoreNoTx, ' + quotename(name) + ' FROM ' + QuoteName(name) + '.dbo.T_SoStore'
FROM sys.databases WHERE database_id > 4 AND state = 0
;
PRINT @sql
EXEC (@sql);