Users with a certain name across the network, with usernames


Please login or register to vote for this query.

(click on this box to dismiss)

Physics Meta

Q&A about the site for active researchers, academics and students of physics

-- result table, don't rename and keep the site column
CREATE TABLE #results (site NVARCHAR(250),
                       accountid INT,
                       displayname NVARCHAR(250));

DECLARE @sql NVARCHAR(MAX) = ''   -- holds build up sql string

-- build one biq union sql, for each db
SELECT @sql = @sql 
+ IIF( LEN(@sql) > 1 
     , 'UNION ALL'
     , 'INSERT INTO #results'
) +
-- here goes the per site query, fully qualify the database objects
SELECT ''' + name + ''', accountid, displayname
  FROM ' + quotename(name) + '.dbo.Users
  WHERE displayname = ''' + ##username:string## + ''' collate sql_latin1_general_cp1_ci_ai
FROM sys.databases
WHERE database_id > 5
  AND (name = 'StackExchange.Meta' OR name NOT LIKE 'StackExchange.Meta%')

-- execute it
EXEC (@sql)

SELECT '' + CAST(accountid AS NVARCHAR) AS 'User',
  string_agg(cast(site as nvarchar(max)), ', ') AS 'Sites',
  string_agg(cast(displayname as nvarchar(max)), ', ') AS 'Usernames'
  FROM #results
  GROUP BY accountid
DROP TABLE #results

Enter Parameters

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