简体   繁体   中英

Multiple Databases on the same SQL Server (MS SQL)

I have a SQL Server with about 100 databases on it. Most of the databases follow the same schema, for example, they have a table named 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!). I've managed to create some dynamic SQL but this seems clunky and I need to develop it.

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).

Variable object names require the use of dynamic SQL, sp_MSforeachdb can simplify this:

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)

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