Q&A for professional and enthusiast programmers
DECLARE @sql nvarchar(MAX) SELECT @sql = COALESCE(@sql + ' UNION ', '') + 'SELECT u.AccountId FROM ' + QUOTENAME(d.name) + '..Users u WHERE u.DisplayName like ''%AsheeshR%'' ' FROM sys.databases d WHERE ((d.name NOT LIKE '%Meta%') or (d.name NOT LIKE '%_Temp%') Or d.name='StackOverflow.Meta') AND (d.name NOT IN ('master', 'model', 'tempdb', 'msdb', 'Data.StackExchange', 'StackExchange.Ai_Temp')) EXEC(@sql)