Reputation: 93348
I'm using SQL Server 2005 and would like to know how I can get a list of all tables with the number of records in each.
I know I can get a list of tables using the sys.tables
view, but I'm unable to find the count.
Thank you
Upvotes: 16
Views: 35913
Reputation: 1428
These all ways will give you the row count in the result set of a select query. SSMS also gives you an option to see the object details via: "Object Explorer Details" pane. This is available for 2005 and all versions after that
Object Explorer Details is a component of SQL Server Management Studio. It provides a tabular view of all the objects in the server and presents a user interface to manage them.
To reach "Object Details Window": Click Object you want to see details for in "Object Explorer" pane and press F7. Read More: https://technet.microsoft.com/en-us/library/ms191146(v=sql.90).aspx
Pros:
Note: You might not have Row Count coming in the Object Details pane by default, you can click on the column header and bring it in.
Upvotes: 1
Reputation: 291
This is my method:
create table #rowcount (tablename varchar(128), rowcnt int)
exec sp_MSforeachtable
'insert into #rowcount select ''?'', count(*) from ?'
select * from #rowcount
order by tablename
drop table #rowcount
works like a charm
Upvotes: 1
Reputation: 551
For what it's worth, the sysindexes system table is deprecated in SQL 2008. The above still works, but here's query that works going forward with SQL 2008 system views.
select
schema_name(obj.schema_id) + '.' + obj.name,
row_count
from (
select
object_id,
row_count = sum(row_count)
from sys.dm_db_partition_stats
where index_id < 2 -- heap or clustered index
group by object_id
) Q
join sys.tables obj on obj.object_id = Q.object_id
Upvotes: 22
Reputation: 119806
I might add that sysindexes.rows is an approximation of the number of rows. I'd run a DBCC UPDATEUSAGE
if you need a more accurate value. We had this issue on a DB with tables containing over 47-50 million rows and we thought we'd lost around half a million from each of them.
Upvotes: 5
Reputation: 3394
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
Upvotes: 42
Reputation: 6406
Perhaps something like this:
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
Upvotes: 3