我們都知道用聚合函數(shù)count()可以統(tǒng)計表的行數(shù)。如果需要統(tǒng)計數(shù)據(jù)庫每個表各自的行數(shù)(DBA可能有這種需求),用count()函數(shù)就必須為每個表生成一個動態(tài)SQL語句并執(zhí)行,才能得到結(jié)果。以前在互聯(lián)網(wǎng)上看到有一種很好的解決方法,忘記出處了,寫下來分享一下。
該方法利用了sysindexes 系統(tǒng)表提供的rows字段。rows字段記錄了索引的數(shù)據(jù)級的行數(shù)。解決方法的代碼如下:
復(fù)制代碼 代碼如下:
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
復(fù)制代碼 代碼如下:
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或者視圖,與其它查詢結(jié)合使用。
新聞熱點
疑難解答
圖片精選