0

How Can i iterate thru the all my DB's and get a row count for each employee table? Each client is has there own DB, need to find the total employees in each DB.

Been trying to figure out how to use sp_MSforeachdb

sp_MSforeachdb 
@command1 = 'select count(*) from employee'

Can output in seperate tables or would be good in one table wiht the DB name.

Yogurt The Wise
  • 4,379
  • 4
  • 34
  • 42

2 Answers2

1

You need to tell it which database to use first (it's in ?):

EXEC sp_MSforeachdb
@command1='use ?; select count(*) from employee'  
1

How about

    DECLARE @sql nvarchar(1000)
    SET @sql = 'Use [?];'
      + 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''dbo'' AND  TABLE_NAME = ''employee''))'
      + ' BEGIN'
      + ' SELECT COUNT(*) from [employee]'
      + ' END'
   exec sp_MSforeachDB @sql

TABLE_SCHEMA = ''dbo'' is optional here in most cases...

Yogurt The Wise
  • 4,379
  • 4
  • 34
  • 42
perfectionist
  • 4,256
  • 1
  • 23
  • 34
  • 1
    Thanks to [joew's blog](http://weblogs.sqlteam.com/joew/archive/2008/08/27/60700.aspx) for syntax for "use [?];" and to [akmad on another stack overflow question](http://stackoverflow.com/questions/167576/sql-server-check-if-table-exists) for the check if a table exists. – perfectionist Jan 19 '12 at 22:18
  • Thanks very much. I also added to mine ''?'' to the select. SELECT ''?'',COUNT(*) to get the table names. Those are single quotes. – Yogurt The Wise Jan 19 '12 at 22:45