Count Rows in all the Tables of a SQL Server Database

To get an accurate value of all the rows in a SQL Server table, use DBCC UPDATEUSAGE. DBCC UPDATEUSAGE corrects the rows, used pages, reserved pages, leaf pages and data page counts for each partition in a table or index. Here’s a query that first uses DBCC UPDATEUSAGE and then count all the rows in all the tables of a database using the undocumented stored procedure sp_msForEachTable

USE AdventureWorks
GO
DECLARE
@DynSQL NVARCHAR(255)
SET @DynSQL = 'DBCC UPDATEUSAGE (' + DB_NAME() + ')'
EXEC(@DynSQL)

EXEC sp_msForEachTable
'SELECT PARSENAME(''?'', 1) as TableName,
COUNT(*) as NumberOfRows FROM ?'

OUTPUT (Partial)

COUNT ROWS

3 comments:

  1. Suggestion for a new Blog Title: "How to kill larges Databases 101"

    ReplyDelete
  2. Hey..i am also looking for the same topic.
    thanks for sharing with us all.

    ReplyDelete
  3. Another method is

    select object_name(id) as table_name, rows from sys.sysindexes
    where indid<2
    order by table_name

    ReplyDelete