1

I have hundreds of databases on the same SQL server (SQL2012), they all have the same basic structure and I'm trying to get the average number of 'Contacts' our databases.

I can run a sp_MSforeachdb query that presents a list of how many contacts are in the contacts table, but I need to then average out the result. Any guidance on doing this.

This is the query I've got so far:

exec sp_MSforeachdb
'use ?
IF DB_NAME() NOT IN ( "model","tempdb","master","msdb")
select count (CONTACTID) as TotalContacts from contact_tbl '

I appreciate it's likely fairly basic stuff, but I'm new here and I've googled the crap out of it and tried a lot of different suggestions from here and other places with no joy.

Any help would be appreciated.

4

1 回答 1

1

你需要一个临时表。将Sp_msforeachdb程序结果插入一个临时表并求平均值

IF Object_id('tempdb..#avg') IS NOT NULL
  DROP TABLE #avg

CREATE TABLE #avg(cnt INT)

INSERT INTO #avg(cnt)
EXEC Sp_msforeachdb
  'use ?
    IF DB_NAME() NOT IN ( "model","tempdb","master","msdb")
    select count (CONTACTID) as TotalContacts from contact_tbl '

SELECT Avg(cnt)
FROM   #test 
于 2016-11-22T14:31:59.343 回答