简体   繁体   English

从具有特定名称的所有数据库的所有表中选择

[英]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 . 数据库每天由ISA创建,其名称由掩码ISALOG_ current_date _WEB_000生成。 Each database contains table WebProxyLog . 每个数据库都包含表WebProxyLog Total count of databases is 60. My goal is to query WebProxyLog table in all databases or in databases of specific dates. 数据库总数为60。我的目标是在所有数据库或特定日期的数据库中查询WebProxyLog表。 Something like foreach loop: 类似于foreach循环:

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. 有一个未记录的存储过程,称为sp_MSForEachDB,但是,我不会急于使用未记录的功能。 This can by done by using dynamic SQL that gets the databases names from sys.DataBases system table: 这可以通过使用从sys.DataBases系统表获取数据库名称的动态SQL来完成:

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. 一旦打印了sql并对其进行了测试,就可以删除print行并取消对exec行的注释。

Further reading - Aaron Bertrand's Bad habits to kick : relying on undocumented behavior And his answer to a question on SO about sp_MSForEachDB. 进一步阅读-亚伦·贝特朗(Aaron Bertrand)的不良习惯:依赖未记录的行为,以及对关于sp_MSForEachDB的问题的回答

Edit: small correction of SELECT: 编辑: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? 结果将查询列表打印到表中,对不对?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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