Get record count for each table in a database

อยากรู้ว่าแต่ละ table ใน database ของ MS SQL Server มีกี่ record แล้วเนี่ย จะทำอย่างไรดีน้อ
วิธีแรก

1
SELECT Count(*)

แต่ถ้ามีหลาย 100 table ล่ะ จะทำที่ละ table คงจะไม่ไหว

วิธีที่สอง Store Procedure

1
exec sp_msforeachtable @command1="SELECT '?' AS TableName, COUNT(*) as TblRowCount FROM ? ORDER BY TableName"

แต่ก็นานอยู่ดีกว่าจะได้

วิธีที่สาม เป็นวิธีใช้ประยุกต์ใช้ System Table ให้เกิดประโยชน์ครับ (มีเค้าอยู่ก็เอามาใช้ประโยชน์หน่อย)

1
2
3
4
5
6
7
8
9
ELECT CONVERT(char(10), t.TABLE_SCHEMA) AS Owner,
CONVERT(char(25), t.TABLE_NAME) AS 'TABLE Name',
MAX(i.[rows]) AS 'Record COUNT'

FROM sysindexes i INNER JOIN INFORMATION_SCHEMA.TABLES t ON OBJECT_NAME(i.id) = t.TABLE_NAME

WHERE (t.TABLE_TYPE = 'BASE TABLE')
GROUP BY t.TABLE_SCHEMA, t.TABLE_NAME
ORDER BY [Record COUNT] DESC

Written by admin on October 6th, 2008 with no comments.
Read more articles on Database and Programming.

Related articles

No comments

There are still no comments on this article.

Leave your comment...

If you want to leave your comment on this article, simply fill out the next form:

You have to be identified to write a comment.