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.

1
  • Almost all the DB's are the same, only one is different has no employee table. Commented Jan 19, 2012 at 22:00

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks to joew's blog for syntax for "use [?];" and to akmad on another stack overflow question for the check if a table exists.
Thanks very much. I also added to mine ''?'' to the select. SELECT ''?'',COUNT(*) to get the table names. Those are single quotes.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.