I know this question is 5 years old, but I found it through Google, so others can as well.
I recommend the sp_msforeachdb system stored procedure. You do not need to create any other stored procedures or cursors.
Given that your database name table has already been created:
EXECUTE sp_msforeachdb ' USE ? IF DB_NAME() IN( SELECT name DatabaseNames ) BEGIN SELECT ''?'' as 'Database Name' , COUNT(*) FROM MyTableName ; END '
I do this to summarize the counts in many databases that I recovered from several different sites with the same database schema installed.
Example: - Repeat the SQL commands in all site database archives.
PRINT 'Database Name' + ',' + 'Site Name' + ',' + 'Site Code' + ',' + '# Users' + ',' + '# Seats' + ',' + '# Rooms' ... and so on... + ',' + '# of days worked' ; EXECUTE sp_msforeachdb 'USE ? IF DB_NAME() IN( SELECT name FROM sys.databases WHERE name LIKE ''Site_Archive_%'' ) BEGIN DECLARE @SiteName As Varchar(100); DECLARE @SiteCode As Varchar(8); DECLARE @NumUsers As Int DECLARE @NumSeats As Int DECLARE @NumRooms As Int ... and so on ... SELECT @SiteName = OfficeBuildingName FROM Office ... SELECT @NumUsers = COUNT(*) FROM NetworkUsers ... PRINT ''?'' + '','' + @SiteName + '','' + @SiteCode + '','' + str(@NumUsers) ... + '','' + str(@NumDaysWorked) ; END '
The hardest part is single quotes
Joe b
source share