SQL 计算 table 中的行数

SQL count rows in a table

我需要向数据库发送一个 SQL 查询,告诉我 table 中有多少行。我可以用 SELECT 获取 table 中的所有行,然后对它们进行计数,但我不喜欢这样做。有没有其他方法可以向 SQL 服务器询问 table 中的行数?

是的,SELECT COUNT(*) FROM TableName

select sum([rows])
from sys.partitions
where object_id=object_id('tablename')
 and index_id in (0,1)

速度非常快,但很少出现不准确的情况。

使用此查询:

Select
    S.name + '.' + T.name As TableName ,
    SUM( P.rows ) As RowCont 

From sys.tables As T
    Inner Join sys.partitions As P On ( P.OBJECT_ID = T.OBJECT_ID )
    Inner Join sys.schemas As S On ( T.schema_id = S.schema_id )
Where
    ( T.is_ms_shipped = 0 )
    AND 
    ( P.index_id IN (1,0) )
    And
    ( T.type = 'U' )

Group By S.name , T.name 

Order By SUM( P.rows ) Desc

这是查询

select count(*) from tablename

select count(rownum) from studennt

您为什么不直接右键单击 table,然后单击属性 -> 存储,它会告诉您行数。 您可以使用下面的视图中的行数。在 WHERE 子句中使用您的 table 的名字。

SELECT SUM (row_count) 
FROM sys.dm_db_partition_stats 
WHERE object_id=OBJECT_ID('TableName')    
AND (index_id=0 or index_id=1)`

索引统计信息可能需要是最新的,但这将 return 所有表的行数不是 MS_SHIPPED。

select o.name, i.rowcnt 
from sys.objects o join sys.sysindexes i 
on o.object_id = i.id
where o.is_ms_shipped = 0
and i.rowcnt > 0
order by o.name