最新下载
热门教程
- 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9
 - 10
 
快速统计SQL Server每个表行数的方法分享
时间:2022-06-29 07:54:28 编辑:袖梨 来源:一聚教程网
我们都知道用聚合函数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或者视图,与其它查询结合使用。
相关文章
- 我的世界创造模式快捷栏怎么保存 mc物品栏管理技巧 11-04
 - 我的世界怎么重新加载区块 mc显示错误技巧解决方法 11-04
 - 我的世界超级敌对模式是什么 mc特殊事件机制说明 11-04
 - 快来当领主阿瑞斯强度怎么样 11-04
 - 命运圣契伊丽丝技能效果如何 11-04
 - 镭明闪击塔攻怎么玩 11-04