CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Darrell Norton's Blog [MVP]

Fill in description here...

Get a record count for all tables in a database

I developed this stored proc after a testing group said that I had not included required data (data in the database for the application to work properly) in a deployment. It also comes in handy to make sure you’ve copied all records from one database to another.

To use, just type GetRecordCountsForAllTables in Query Analyzer and you will get a record set returned with a row for every table in the current database with the owner, table name, and row count. Perfect for copying and pasting to Excel.

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetRecordCountsForAllTables]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure
[dbo].[GetRecordCountsForAllTables]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET
ANSI_NULLS OFF
GO

CREATE  Procedure dbo.GetRecordCountsForAllTables AS

select  'Owner'=convert(char(10),t.TABLE_SCHEMA),
      '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



Comments

Darrell said:

I use the sp_msForEachTable stored proc to run DDL commands on every table (say I need to update all the timestamps in every row in every table for some reason).

The stored proc I show will be faster for large record counts or numbers of tables since I directly access the sysindexes table for record count info.
# June 21, 2004 9:35 PM

deva said:

great script
# October 12, 2004 9:52 AM

RT said:

Hi
Im still a novice in ms access,
can the codes above be use for in microsoft
access if so where do i need to place the
codes, thanks
# October 13, 2004 1:34 PM

Darrell said:

No, the above code would not work for Access. And I don't know what would work since I haven't done any Access development in 4 years.

You may want to check out the Microsoft Access newsgroup:
http://groups.google.com/groups?hl=en&lr=&group=microsoft.public.access
# October 14, 2004 1:54 AM

Jason said:

This ROCKS!

Thank you
# December 2, 2004 12:31 PM

Jens said:

made my day ....
# February 9, 2005 4:44 AM

Michael said:

Nice bit of code :)
# March 23, 2005 8:21 AM
Check out Devlicio.us!