How to count or know the number of rows a table has without scaning all the table, maybe using ROW_NUMBER
?
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;