在 SQL Server 管理中,統計資料庫內每張表的行數是 DBA 常見的需求。雖然傳統做法是使用 COUNT(*) 聚合函數,但對於大型資料庫逐表執行動態 SQL 不僅緩慢,還會佔用大量資源並對使用者表加鎖,影響效能。本文介紹一種利用系統目錄視圖 sysindexes 的 rows 欄位快速獲取行數的技巧,速度極快且零干擾。
SQL Server 內部維護著索引與堆的統計資訊。sysindexes 系統表(或相容性視圖)中的 rows 欄位記錄了對應索引或堆的資料列數量。每張表至少擁有一個堆或叢集索引,其 indid 值為 0 或 1。因此,只要篩選 indid <= 1,即可精準獲取每張表的一行統計記錄。
SELECT
SCHEMA_NAME(t.schema_id) AS [Schema],
t.name AS TableName,
i.rows AS RowCount
FROM sys.tables AS t
JOIN sysindexes AS i ON t.object_id = i.id
WHERE i.indid <= 1
ORDER BY RowCount DESC;
查詢連接 sys.tables 取得表名與結構描述 ID,透過 SCHEMA_NAME() 函數解析結構描述名稱,最後依行數降冪排序,方便快速識別大表。
| Schema | TableName | RowCount |
|---|---|---|
| Production | TransactionHistory | 113,443 |
| Person | Address | 19,614 |
| Sales | StoreContact | 753 |
| Production | ProductProductPhoto | 504 |
| Sales | Store | 701 |
| Production | ProductPhoto | 101 |
| Production | ProductReview | 4 |
| Person | AddressType | 6 |
sysindexes 為相容性視圖,新版本建議改用 sys.partitions 配合 index_id IN (0,1) 以獲得長期支援。COUNT(*)。掌握此技巧,即可輕鬆建立輕量級的資料表行數監控儀表板,為資料庫容量規劃與效能調優提供即時決策依據。