SQL Script to Get Row Count of All Tables in Database

There is an undocumented built-in stored procedure than iterates over all tables in a database and executes a SQL script "sp_msforeachtable" which makes the job pretty straightforward:

sp_msforeachtable "SELECT '?', COUNT(*) FROM ?"


Another nifty little sproc to use is the sp_spaceused which will besides row count return reserved size, data size, index size and unused size of a given table. Combine the two and you get a pretty nice list:

CREATE TABLE #TempTable
(
    tableName varchar(100),
    numberofRows varchar(100),
    reservedSize varchar(50),
    dataSize varchar(50),
    indexSize varchar(50),
    unusedSize varchar(50)
)
GO

EXEC sp_msforeachtable "INSERT #TempTable EXEC sp_spaceused '?'"
GO

SELECT * FROM #TempTable

DROP TABLE #TempTable
GO
About these ads

One Comment on “SQL Script to Get Row Count of All Tables in Database”

  1. Hank says:

    Thanks, this was the simplest and least convoluted way I’ve seen this done!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.