获得表行计数

如果 table_name 被你要查询的表替换,则可以使用以下示例查找数据库中特定表的总行数:

SELECT COUNT(*) AS [TotalRowCount] FROM table_name;

通过使用以下脚本基于表的 HEAP(index_id = 0)或集群聚簇索引(index_id = 1)连接回表的分区,还可以获取所有表的行计数:

SELECT  [Tables].name                AS [TableName],
        SUM( [Partitions].[rows] )    AS [TotalRowCount]
FROM    sys.tables AS [Tables]
JOIN    sys.partitions AS [Partitions]
    ON  [Tables].[object_id]    =    [Partitions].[object_id]
    AND [Partitions].index_id IN ( 0, 1 )
--WHERE    [Tables].name = N'table name' /* uncomment to look for a specific table */
GROUP BY    [Tables].name;

这是可能的,因为每个表本质上都是一个分区表,除非向其添加额外的分区。该脚本还具有不干扰对表行的读/写操作的好处。