• anthony.green - Wednesday, December 20, 2017 9:27 AM

    Do you need the exact row counts or can a very close approximate do, if so I would join back to sys.partitions where the index id is 0 or 1 and pull the row count out via that metadata view instead.  The documentation states the values are "approximate" but I have yet to see a difference when querying select count(*) vs the view

    Got the from Uncle Google and just tweaked it a little bit 
    DECLARE @TableRowCounts TABLE ([databaseName] Varchar(100),[SchemaName] VARCHAR(128),[TableName] VARCHAR(128), [RowCount] INT) ;
        INSERT INTO @TableRowCounts ([databaseNAme],[SchemaName],[TableName], [RowCount])
        EXEC sp_MSforeachdb 'SELECT ''?'',s.Name,TBL.name, SUM(PART.rows) AS rows
                            FROM sys.tables TBL
                            INNER JOIN sys.schemas s on TBL.schema_id=s.schema_id
                            INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id
                            INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id
                            AND PART.index_id = IDX.index_id
                            WHERE IDX.index_id < 2
                            GROUP BY TBL.object_id, s.Name, TBL.name;' ;
                            
    Select SchemaName+'.'+TableName as TableName, [RowCount] 
    From @TableRowCounts
    where databaseName = 'LPDB_API'
    order by SchemaName, TableName