Navigation

Search

Categories

On this page

Count the number of rows in every table in a database

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 378
This Year: 6
This Month: 1
This Week: 0
Comments: 17

Sign In
Pick a theme:

# Thursday, June 03, 2010
Thursday, June 03, 2010 8:35:43 PM (GMT Daylight Time, UTC+01:00) ( SQL )


To get an accurate value of all the rows in a SQL Server table, use DBCC UPDATEUSAGE. 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.

DECLARE @DynSQL NVARCHAR(255) 
SET @DynSQL = 'DBCC UPDATEUSAGE (' + DB_NAME() + ')' 
EXEC(@DynSQL) 
EXEC sp_msForEachTable'SELECT PARSENAME(''?'', 1) as TableName,COUNT(*) as NumberOfRows FROM ?'

image

Here is another method of doing this:

CREATE  Procedure dbo.RecordCountForAllTables 
AS
SELECT 
      'Table Name'=convert(char(25),t.TABLE_NAME),
      'Record Count'=max(i.rows)
FROM sysindexes i, INFORMATION_SCHEMA.TABLES t
WHERE t.TABLE_NAME = object_name(i.id)
      and t.TABLE_TYPE = 'BASE TABLE'
GROUP BY t.TABLE_SCHEMA, t.TABLE_NAME
GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
 
Exec RecordCountForAllTables