TechAid24

Your Technical Consultant

Get All Table Names with Row Counts in SQL Server : One Query to Rule Them All

Posted on by Selim Ahmed 1 minute read

In this tutorial, you will learn how to get all table names with row counts in SQL Server Database. Before we start, if you need to download the Crystal Report developer for VS 2019, please go through the following link: Crystal Reports for Visual Studio 2019.

If you are looking for the row count of all tables in all databases (which was what I was looking for), then I found this combination of this and this to work. No idea whether it is optimal or not:

SET NOCOUNT ON
DECLARE @AllTables table (DbName sysname,SchemaName sysname, TableName sysname, RowsCount int )
DECLARE @SQL nvarchar(4000)
SET @SQL='SELECT ''?'' AS DbName, s.name AS SchemaName, t.name AS TableName, p.rows AS RowsCount FROM [?].sys.tables t INNER JOIN sys.schemas s ON t.schema_id=s.schema_id INNER JOIN [?].sys.partitions p ON p.OBJECT_ID = t.OBJECT_ID'

INSERT INTO @AllTables (DbName, SchemaName, TableName, RowsCount)
EXEC sp_msforeachdb @SQL


SET NOCOUNT OFF
SELECT DbName AS [Database Name],SchemaName AS [Schema Name],TableName AS [Table Name], SUM(RowsCount) AS [Total Rows Count]
FROM @AllTables
WHERE RowsCount > 0
GROUP BY DbName, SchemaName, TableName
ORDER BY DbName, SchemaName, TableName
Table Names with Row Counts in SQL Server

Tags:

Selim Ahmed

Thank you for visiting my personal blog. I’m Selim Ahmed, a tech-savvy who loves to learn a new technology every day. Innovation, research, and development is my daily activities. I love to work in a place where I can learn, innovate, and develop new things.Please feel free to reach me on any comments and feedback you have. I would be more than glad to listen and reply.

Leave a Reply

Your email address will not be published. Required fields are marked *