Q&A for professional and enthusiast programmers
/* Inspiration for cross-site query from: Mark Hurd, http://data.stackexchange.com/stackoverflow/query/69700/generate-emailhash-comparison Tim Stone, http://data.stackexchange.com/stackoverflow/query/72411 */ /* #table style tables are available to the dynamic SQL. the best bet is to build a cursor of all databases in the system that matter. The easist way to do that is to look for all databases that come in pairs, a regular database and the corresponding meta site database. E.g. - StackExchange.Codereview.Meta - StackExchange.Codereview There are other databases in the system tables, but they do not have a matching meta database. Unfortunately, the site Meta.stackexchange.com does not have a meta, so add it in. */ declare SITES cursor for select Substring(Name, 0, Len(Name) - 4) from sys.Databases where Name like '%.Meta' and not Name = 'StackExchange.Meta' UNION select 'StackExchange.Meta' create table #sitestats ( Site NVarchar(200), Reputation Int, Name NVarchar(50) ); declare @sitedbname as NVarchar(100), @query as NVarchar(1000) ; open SITES fetch next from SITES into @sitedbname while @@FETCH_STATUS = 0 BEGIN declare @org as NVarchar(100), @http as NVarchar(100), @pos as int; -- convert the DBName in to a URL for the result set. select @org = lower(@sitedbname), @http = 'http://', @pos = CharIndex('.', @sitedbname); if @pos > 0 begin select @http = @http + substring(@org, @pos + 1, len(@org) - @pos) + '.', @org = left(@org, @pos - 1) end select @http = @http + @org + '.com' print 'Processing site ' + @sitedbname + ' -> ' + @http --Add whatever sub-URL you want to the http url: select @http = @http + '/users/' -- build and run your dynamic query. Note how you prefix the tables you need set @query = ' insert into #sitestats select ''' + @http + ''' + cast (Id as NVarchar(10)) + ''|'' + ''' + @sitedbname + ' -> '' + DisplayName , Reputation, DisplayName FROM [' + @sitedbname + ']..Users where Reputation = ( select max(Reputation) from [' + @sitedbname + ']..Users)' ; EXEC sp_executesql @query fetch next from SITES into @sitedbname END close SITES deallocate SITES ; select * from #sitestats