您现在的位置是:网站首页> 编程资料编程资料
SQL Server中统计每个表行数的快速方法_MsSql_
2023-05-26
597人已围观
简介 SQL Server中统计每个表行数的快速方法_MsSql_
我们都知道用聚合函数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或者视图,与其它查询结合使用。
您可能感兴趣的文章:
相关内容
- Sql Server中的事务介绍_MsSql_
- Sql Server中的视图介绍_MsSql_
- SQL Server数据库中的存储过程介绍_MsSql_
- SQL Server 2012 创建定时作业(图文并茂,教你轻松快速创建)_MsSql_
- sql server启动不了, MSSQL 18052错误: 9003,严重度: 20,状态: 1 ._MsSql_
- 简单判断MSSQL数据库版本(2000或者2005)_MsSql_
- win2008 r2 安装sql server 2005/2008 无法连接服务器解决方法_MsSql_
- 必须会的SQL语句(八) 数据库的完整性约束_MsSql_
- 必须会的SQL语句(七) 字符串函数、时间函数_MsSql_
- 必须会的SQL语句(六) 数据查询_MsSql_
