简体   繁体   中英

How to get table row count in SQL Server?

There's a requirement where I need to get the table row count information without using count function. Currently I have used the below code to achieve it:

SELECT
    CONCAT(schemas.name, '.', tables.name) as tableName, 
    partitions.rows AS tableRowCount
FROM
    sys.partitions
JOIN
    sys.tables ON tables.object_id = partitions.object_id
JOIN
    sys.schemas ON tables.schema_id = schemas.schema_id

But for some reason, this query is not working properly as expected. Having said that, in some cases tableRowCount is different if the same is checked using the count function.

Is there a way to overcome this challenge?

Please note I tried using sys.dm_db_partition_stats table as well.

However, I get this error:

Msg 104385, Level 16, State 1, Line 9
Catalog view 'dm_db_partition_stats' is not supported in this version.

Please help.

This should be much faster than using COUNT .

SELECT SUM(p.rows) FROM sys.partitions AS p
INNER JOIN sys.tables AS t ON p.[object_id] = t.[object_id]
INNER JOIN sys.schemas AS s ON s.[schema_id] = t.[schema_id]
WHERE t.name = N'(yourtable)' AND s.name = N'dbo' AND p.index_id IN (0,1);

Note that this approach is in no way portable between RDBMSs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM