Twitter

Follow SQLQuill on Twitter

Subscribe

MN Pass

Get Fairly Accurate Table Counts

Here’s a simple script that I use often – a quick hitter to find table row counts, that doesn’t use the Select Count(*). It uses the sysindexes table thus the reason it’s called “fairly accurate”.

SELECT
 [TableName] = so.name,
 [RowCount] = MAX(si.rows)
FROM
 sysobjects so,
 sysindexes si
WHERE
 so.xtype = 'U'
 AND
 si.id = OBJECT_ID(so.name)
GROUP BY
 so.name
ORDER BY
 2 DESC

Table Size

--This will give you the amount of disk space that each table uses in a database.

SET NOCOUNT ON
DECLARE @cmdstr varchar(100)
DECLARE @Sort bit

CREATE TABLE #TempTable
 ( [Table_Name] varchar(50),
 Row_Count int,
 Table_Size varchar(50),
 Data_Space_Used varchar(50),
 Index_Space_Used varchar(50),
 Unused_Space varchar(50)
 )

SELECT @cmdstr = 'sp_msforeachtable ''sp_spaceused "?"'''
INSERT INTO #TempTable EXEC(@cmdstr)

--Use one of these depending what you are looking for.
--SELECT * FROM #TempTable ORDER BY Table_Name
SELECT * FROM #TempTable ORDER BY Len(Table_Size) DESC, Table_Size DESC

--DROP TABLE #TempTable