April 28, 2010

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


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

3 Responses to "Count Rows in all the Tables of a SQL Server Database"
  1. Anonymous said...
    April 29, 2010 at 9:40 AM

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

  2. John David said...
    May 2, 2010 at 11:19 PM

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

  3. Madhivanan said...
    July 6, 2010 at 12:16 AM

    Another method is

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

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions