简体   繁体   中英

SQL get table row count for specific table in DB

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.

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

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

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

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