简体   繁体   English

同一SQL Server上的多个数据库(MS SQL)

[英]Multiple Databases on the same SQL Server (MS SQL)

I have a SQL Server with about 100 databases on it. 我有一个SQL Server,上面有大约100个数据库。 Most of the databases follow the same schema, for example, they have a table named dbo.Files. 大多数数据库遵循相同的模式,例如,它们有一个名为dbo.Files的表。

I want to write a query which will return me the UNIONed result of all the dbo.Files across all databases, but without specifically referencing the tables themselves (there are too many!). 我想写一个查询,它将返回所有数据库中所有dbo.Files的UNIONed结果,但没有专门引用表本身(有太多!)。 I've managed to create some dynamic SQL but this seems clunky and I need to develop it. 我已经设法创建了一些动态SQL,但这看起来很笨重,我需要开发它。

SELECT 'SELECT count(*) FROM ' + '[' + name + ']' + '.dbo.Files'    
FROM master..sysdatabases   

The query should also account for the fact that not all of the databases have a dbo.Files table (and maybe output a line saying as much). 该查询还应考虑到并非所有数据库都具有dbo.Files表(并且可能输出一行说明的事实)。

Variable object names require the use of dynamic SQL, sp_MSforeachdb can simplify this: 变量对象名称需要使用动态SQL, sp_MSforeachdb可以简化这个:

sp_MSforeachdb 'USE [?]
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.tables WHERE TABLE_NAME = ''Files'' AND TABLE_TYPE = ''BASE TABLE'' AND TABLE_SCHEMA = ''dbo'')
    PRINT ''SELECT count(*) FROM [?].dbo.Files''
ELSE
    PRINT ''no table in ?''
'

( ? is replaced with each db name) ?替换为每个db名称)

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

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