Vidhya Sagar – Blog One Stop for SQL Server related Queries

13Jun/09

Script to get row count for all the tables in all the databases

I've written this script  to get details of row count in all the tables in all the database including the system database. You can modify the script  to exclude system database if you  don't need details for that. You can see that I haven't use COUNT() function to get these values, If I run using this function for all the db then it will take more time and resource.

Applies to:

  • SQL Server 2000
  • SQL Server 2005
  • SQL Server 2008

Script

SET NOCOUNT ON
DECLARE @query VARCHAR(4000)
DECLARE @temp TABLE (DBName VARCHAR(200),TABLEName VARCHAR(300), COUNT INT)
SET @query='SELECT  ''?'',sysobjects.Name, sysindexes.Rows
FROM   ?..sysobjects INNER JOIN ?..sysindexes ON sysobjects.id = sysindexes.id
WHERE  type = ''U''  AND sysindexes.IndId < 2 order by sysobjects.Name'
INSERT @temp
EXEC sp_msforeachdb @query
SELECT * FROM @temp WHERE DBName <> 'tempdb' ORDER BY DBName

Output

rowcount-alldb

VN:F [1.9.3_1094]
Rating: 4.5/5 (2 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)
Script to get row count for all the tables in all the databases, 4.5 out of 5 based on 2 ratings
Comments (2) Trackbacks (0)
  1. I get the following while executing your script in SQL 2000
    EXECUTE cannot be used as a source when inserting into a table variable.

  2. Some times it happens in sql2k when it has more rows and also for other reasons. I’ve replaced table variable with temp table, now it should run fine, try the query below

    SET NOCOUNT ON
    DECLARE @query VARCHAR(4000)
    IF EXISTS (SELECT 1 FROM tempdb..sysobjects WHERE name ='##temp')
    DROP TABLE ##temp
    CREATE TABLE ##temp (DBName VARCHAR(200),TABLEName VARCHAR(300), COUNT INT)
    SET @query='SELECT ''?'',SO.Name, SI.Rows
    FROM ?..sysobjects AS SO INNER JOIN ?..sysindexes AS SI ON SO.id = SI.id
    WHERE SO.type = ''U'' AND SI.IndId < 2 order by SO.Name'
    INSERT ##temp
    EXEC sp_msforeachdb @query
    SELECT * FROM ##temp WHERE DBName 'tempdb' ORDER BY DBName
    DROP TABLE ##temp


Leave a comment


No trackbacks yet.