Many times using a cursor for this sort of thing seems like the only way to pull this off. sp_msforeachdb is just a cursor too. Neither of these approaches is bad but if you have a lot of databases it can be really slow. As another option you can use FOR XML to build a dynamic string.
Something like this. Once you are sure the dynamic string is correct just uncomment the sp_executesql. 🙂
declare @SQL nvarchar(max)
;with DatabaseList as
(
select name
from sys.databases
where database_id > 4
and name not in ('ReportServer', 'ReportServerTempDB')
)
select top 1 @SQL =
stuff((
select 'union all select Col1, col2, col3, Col4, col5 from ' + name + '.dbo.YourTable '
from DatabaseList
FOR XML PATH('')), 1, 10, '')
from DatabaseList
select @SQL
--exec sp_executesql @statement = @SQL
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/