Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Total count of all rows in all tables

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-03-04 : 21:39:56
Scott writes "What's the best way to create a stored procedure to count all rows of every table in a given database ? I know I've seen this done before but can't find the code anywhere."

Merkin
Funky Drop Bear Fearing SQL Dude!

4970 Posts

Posted - 2002-03-04 : 21:57:10
Funny you mention that, I just wrote a quick script the other day that does it.

See how this comes out...



/*-----------------------------------------------------------------
-- Name : Get all table counts
-- Description : This query lists the recordcount from all tables.
--
---------------------------------------------------------------------*/

Create table #Tables (
TbName varchar(1000),
RecCount int NULL

)

Set nocount on

Declare @sql varchar(8000)
Declare @TbName VarChar(1000)
Declare @RecCount int
Declare @ColumnName varchar(100)
Declare @LastUpdated DateTime

Declare Cursor1 Cursor FOR

Select name from Sysobjects
WHERE type = 'u'
Order by name

Open Cursor1
Fetch Next From Cursor1 Into @TbName
While @@Fetch_Status = 0
BEGIN
SELECT @ColumnName = NULL


SELECT @ColumnName = (
Select TOP 1 Column_Name FROM
INFORMATION_SCHEMA.Columns
WHERE Table_Name = @TBName
and Column_Name like '%Updated'
)



Select @SQL = 'Insert Into #Tables (TbName, RecCount) Select '''
SELECT @SQL = @SQL + @TbName + ''', Count(*) '
SELECT @SQL = @SQL + ' FROM '
SELECT @SQL = @SQL + @TbName

Exec(@sql)



Fetch Next From Cursor1 Into @TbName
END
Close Cursor1
Deallocate Cursor1

Select *
from #Tables

Drop Table #Tables

Set nocount off



Damian

Edited by - merkin on 03/04/2002 22:04:40
Go to Top of Page

Onamuji
Aged Yak Warrior

504 Posts

Posted - 2002-03-05 : 08:55:02
yucky cursors ... SQL Server 2000 version .. .could be changed easily to use temp table instead...

SET NOCOUNT ON

DECLARE @tables TABLE (TABLE_NAME VARCHAR(256), ROW_COUNT BIGINT)
DECLARE @row_count BIGINT
DECLARE @table VARCHAR(256)
DECLARE @sql NVARCHAR(4000)

INSERT INTO @tables (TABLE_NAME, ROW_COUNT)
SELECT TABLE_NAME,
-1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

WHILE (SELECT COUNT(*) FROM @tables WHERE ROW_COUNT = -1) > 0
BEGIN
SELECT @table = TABLE_NAME
FROM @tables
WHERE ROW_COUNT = -1

SET @sql = 'SELECT @row_count = COUNT_BIG(*) FROM ' + @table
EXEC sp_executesql @sql, N'@row_count BIGINT OUTPUT', @row_count OUTPUT

UPDATE @tables
SET ROW_COUNT = @row_count
WHERE TABLE_NAME = @table
END

SELECT * FROM @tables


- Onamuji
Go to Top of Page
   

- Advertisement -