zoukankan      html  css  js  c++  java
  • 一种快速统计SQL Server每个表行数的方法

    我们都知道用聚合函数count()可以统计表的行数。如果需要统计数据库每个表各自的行数(DBA可能有这种需求),用count()函数就必须为每个表生成一个动态SQL语句并执行,才能得到结果。以前在互联网上看到有一种很好的解决方法,忘记出处了,写下来分享一下。

    该方法利用了sysindexes 系统表提供的rows字段。rows字段记录了索引的数据级的行数。解决方法的代码如下:

    1
    2
    3
    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或者视图,与其它查询结合使用。
  • 相关阅读:
    必须使用"角色管理工具"安装或配置microsoft.net framework 3.5
    RAC和ASM环境下修改控制文件control file
    Spring Boot热部署(springloader)
    Spring Boot返回json数据及完美使用FastJson解析Json数据
    Windwos配置Maven环境变量
    Spring Boot之HelloWorld
    查询SQLSERVER执行过的SQL记录
    《老妈语录》 读后感
    MySql安装
    MyEclipse中常用的快捷键大全
  • 原文地址:https://www.cnblogs.com/liqing1009/p/12574242.html
Copyright © 2011-2022 走看看