Count the Number of Records for each Database Tables in MS SQL
Please read our Disclaimer
Works With
-Microsoft SQL Server 2016 (RTM) – 13.0.1601.5 (X64)
-Microsoft SQL Server 2008 (RTM) – 10.0.1600.22 (X64)
In case you need a quick run of how many records (or rows) are there in your database tables.
Command:
--Create a temporary storage to store our result
CREATE TABLE #tmpList
(
tableName VARCHAR(255),
recordCount INT
)
--We will loop thru using an MS SQL built-in stored procedure
EXEC sp_MSForEachTable @command1 = 'INSERT #tmpList (tableName, recordCount) SELECT ''?'', COUNT(*) FROM ?'
--View the result
SELECT tableName, recordCount FROM #tmpList ORDER BY tableName ASC
--Release the temporary storage
DROP TABLE #tmpList
Steps and Sample Usage:
- Open and log into your SQL Management Studio
- Open a New Query Windows or (CTRL+N)
- Copy and Paste the code block above to your Query Window
- Execute the query by pressing F5.
Use Case:
- Use when you need a quick overview of how many records exists in your database tables.
Sample Data:
-AdventureWorks2016 Database