Distinct Stack-wide Accounts


Please login or register to vote for this query.

(click on this box to dismiss)

Stack Overflow

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'
    select 'StackExchange.Meta'

create table #sitestats (
    AccountId Integer not null primary key);
declare @sitedbname as NVarchar(100),
        @query as NVarchar(1000)
open SITES

fetch next from SITES into @sitedbname
while @@FETCH_STATUS = 0

    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)
    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 distinct AccountId
           FROM [' + @sitedbname + ']..Users
           where AccountId not in (select AccountId from #sitestats)
             and AccountId is not null'
    EXEC sp_executesql @query

    fetch next from SITES into @sitedbname

close SITES
deallocate SITES

select count (*) as [Unique Account Count]
from #sitestats

Enter Parameters

Switch to meta site
loading Hold tight while we fetch your results