我們都知道用聚合函數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
復制代碼 代碼如下:
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或者視圖,與其它查詢結合使用。
新聞熱點
疑難解答