Is there a way in SMSS to detect whether a table has any records? I need to get a list of tables that have records. perhaps there is a sql statement that will do the trick?
Asked
Active
Viewed 2.8k times
21
-
https://stackoverflow.com/questions/17748417/sql-server-management-studio-finding-all-non-empty-tables/50602998#50602998 – jophab May 30 '18 at 11:35
5 Answers
27
Try this - gives you the table name and the row count:
SELECT
t.NAME AS TableName,
SUM(p.rows) AS [RowCount]
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE
i.index_id <= 1
GROUP BY
t.NAME, i.object_id, i.index_id, i.name
ORDER BY
SUM(p.rows) DESC
It shows all tables and their row counts in a single output.
marc_s
- 704,970
- 168
- 1,303
- 1,425
-
How can it be restricted to certain DB? If I have on the same sql server more databases with the same table names, the row count will be added together. – Ondrej Peterka Nov 27 '15 at 15:01
-
@OndraPeterka: no, this is always executed in the context of **one database** - and only those tables will be shown. This does **not** show all tables of all databases of a server – marc_s Nov 27 '15 at 15:53
-
20
A simpler syntax:
SELECT
[Name] = o.name,
[RowCount]= SUM(p.row_count)
FROM SYS.DM_DB_PARTITION_STATS p
INNER JOIN SYS.TABLES o ON p.[object_ID] = o.[object_id]
WHERE index_id <= 1 -- Heap or clustered index only
GROUP BY o.name
ORDER BY 2 desc
Hugo Forte
- 4,669
- 5
- 31
- 44
Noel Abrahams
- 7,423
- 3
- 34
- 36
18
As your question specifically mentions SSMS you can also right click the database in object explorer and then from the short cut menu do
Reports -> Standard Reports -> Disc Usage By Table
Martin Smith
- 419,657
- 83
- 708
- 800
3
You can use this stored procedure:
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"
This will return a resultset for each table in the database (each showing the name, and the number of rows, among other information).
Here is how you can put them into a table variable, and order them by the number of rows:
DECLARE @TBL TABLE (
[name] nvarchar(500),
[rows] bigint,
[reserved] nvarchar(500),
[data] nvarchar(500),
[index_size] nvarchar(500),
[unused] nvarchar(500)
)
INSERT INTO @TBL
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"
SELECT * FROM @TBL
ORDER BY [rows] DESC
Gabriel McAdams
- 54,482
- 10
- 60
- 76
0
Hope, It helps you-
SELECT name AS [TableList] FROM SYS.DM_DB_PARTITION_STATS s
INNER JOIN sys.tables t ON t.[object_id] = s.[object_id]
WHERE row_count = 0
This code shows that list of tables, which does not contain any data or row.
Thanks!!!
Nitika Chopra
- 1,121
- 15
- 21