number of rows SQL Server

前端 未结 5 912
挽巷
挽巷 2020-12-31 14:38

How to count or know the number of rows a table has without scaning all the table, maybe using ROW_NUMBER?

5条回答
  •  天涯浪人
    2020-12-31 15:13

    If you need a exact count, you will need to do a COUNT(*) which will scan the clustered index.

    You can get a rough count using the sys.partitions schema, as shown here http://www.kodyaz.com/articles/sql-rowcount-using-sql-server-system-view-sys-partitions.aspx

    Update: To get the count into a variable:

    DECLARE @cnt INT;
    SELECT @cnt = SUM(rows)
    FROM sys.partitions
    WHERE
      index_id IN (0, 1)
      AND object_id = OBJECT_ID('MyDB.dbo.MyTable');
    SELECT @cnt;
    

提交回复
热议问题