简体   繁体   中英

Select from all tables in all databases with specific name

I need to query all the tables with specific name in all databases on server. Databases creates daily by ISA and its names generates by mask ISALOG_ current_date _WEB_000 . Each database contains table WebProxyLog . Total count of databases is 60. My goal is to query WebProxyLog table in all databases or in databases of specific dates. Something like foreach loop:

foreach($db in $databases)
{
   if($db.Name.Contains("_web"))
    {
     SELECT [ClientUserName],[logTime],[uri],[UrlDestHost],[bytesrecvd],[bytessent],[rule]
     FROM [$db].[dbo].[WebProxyLog]
     WHERE [ClientUserName] like ''%username%''
    }
}

Perfect if result of query will be merged in single table or view. Is there a way to perform that?

There is an undocumented stored procedure called sp_MSForEachDB, However, I would not rush to use undocumented features. This can by done by using dynamic SQL that gets the databases names from sys.DataBases system table:

DECLARE @SQL nvarchar(max) = N''


SELECT @SQL = @SQL + 
'UNION ALL 
     SELECT ['+ name +'] As DBName, [ClientUserName],[logTime],[uri],[UrlDestHost],[bytesrecvd],[bytessent],[rule]
     FROM [' + name + '].[dbo].[WebProxyLog]
     WHERE [ClientUserName] like ''%username%''

'
FROM sys.DataBases 
WHERE name LIKE '%ISALOG%WEB%'

SET @SQL = STUFF(@SQL, 1, 10, '') + ' ORDER BY DBName'

PRINT @SQL

--EXEC(@SQL)

Once you've printed the sql and tested it, you can remove the print row and un-comment the exec row.

Further reading - Aaron Bertrand's Bad habits to kick : relying on undocumented behavior And his answer to a question on SO about sp_MSForEachDB.

Edit: small correction of SELECT:

'UNION ALL 
 SELECT [ClientUserName],[logTime],[uri],[UrlDestHost],[bytesrecvd],[bytessent],[rule]
 FROM [' + name + '].[dbo].[WebProxyLog]
 WHERE [ClientUserName] like ''%username%''
'

As result it prints listing of queries to the tables, right?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM