求快速统计SQL Server 某个库里所有表的方法,count() 函数很慢的。

如题所述

我们都知道用聚合函数count()可以统计表的行数。如果需要统计数据库每个表各自的行数(DBA可能有这种需求),用count()函数就必须为每个表生成一个动态SQL语句并执行,才能得到结果。以前在互联网上看到有一种很好的解决方法,忘记出处了,写下来分享一下。
该方法利用了sysindexes 系统表提供的rows字段。rows字段记录了索引的数据级的行数。解决方法的代码如下:
select schema_name(t.schema_id) as [Schema], t.name as TableName,i.rows as [RowCount]
from sys.tables as t, sysindexes as i
where t.object_id = i.id and i.indid <=1
该方法连接了sys.tables视图,从中找出表名和schema_id,再通过schema_name函数获取表的架构名。筛选条件i.indid <=1 只选聚集索引或者堆,每个表至少有一个堆或者聚集索引,从而保证为每个表返回一行。以下是在我的AdventureWorks数据库中运行该查询返回的部分结果:
Schema TableName RowCount
——————– ——————– ———–
Sales Store 701
Production ProductPhoto 101
Production ProductProductPhoto 504
Sales StoreContact 753
Person Address 19614
Production ProductReview 4
Production TransactionHistory 113443
Person AddressType 6
该方法的优点有:
1.运行速度非常快。
2.由于不访问用户表,不会在用户表上放置锁,不会影响用户表的性能。
3.可以将该查询写成子查询、CTE或者视图,与其它查询结合使用。
望采纳
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-02-28
select schema_name(t.schema_id) as [Schema], t.name as TableName,i.rows as [RowCount]

from sys.tables as t, sysindexes as i

where t.object_id = i.id and i.indid <=1

追问

这是要在被查询的那个库上执行吗?

追答

是的

本回答被提问者采纳
第2个回答  2018-04-11

查询系统表吧!

系统表里面有存储表行数的哦!
如果是sqlserver  试一下下面的方法

快速获取表行数的方法

如有疑问,及时沟通!

相似回答