一种快速统计SQL Server每个表行数的方法

我们都知道用聚合函数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

 

该方法的优点有:

  • 运行速度非常快。
  • 由于不访问用户表,不会在用户表上放置锁,不会影响用户表的性能。
  • 可以将该查询写成子查询、CTE或者视图,与其它查询结合使用。

 

Technorati 标签: SQL Server,SQL
posted @ 2013-04-09 23:43  Ken Yang  阅读(10317)  评论(2编辑  收藏  举报