Table row count using 3 different ways

  • Comments posted to this topic are about the item Table row count using 3 different ways

    Mohit Nayyar
    "If I am destined to fail, then I do have a purpose in my life, To fail my destiny"

  • I've always found cursors a really slow way of doing pretty much anything in SQL, to say nothing of being a horror to code if it's big enough.

    There could be a fourth way. Create a temporary table containing the name and object_id values of every user table in the database. Then create a loop to do the following:

    a. Select the name of the table object with the lowest object_id value;

    b. Execute a string of dynamic SQL to count the number of rows in the table bearing the name that you retrieved in step 1;

    c. Delete the record in the temporary table that you've just been looking at;

    d. Repeat until the temporary table is empty;

    You could refine it further by writing the result of the count into a new table (temporary or otherwise). Or even by adding an additional column to the original temporary table and then updating that each time. The only difference is that you wouldn't delete the record once you'd finished with it, merely select the minimum object_id value as long as it was higher than the object_id value you'd just finished with.

    Just a thought 🙂

  • To expand on ianhenderson's way here is the loop without worrying about the lowest id and just grabbing the next one that doesn't have a count.

    DECLARE @TableName VARCHAR(255);

    SELECT TABLE_NAME AS TableName, null AS RowCnt

    INTO #TempTableCounts


    WHERE TABLE_TYPE = 'base table';


    SELECT TOP(1) @TableName = TableName FROM #tempTableCounts WHERE (RowCnt IS NULL);

    EXEC ('UPDATE #TempTableCounts SET RowCnt = (SELECT count(*) FROM ' + @TableName + ') WHERE (TableName = ''' + @TableName + ''')');


    SELECT TableName, RowCnt FROM #TempTableCounts;

    DROP TABLE #TempTableCounts;


  • Does this seemingly simpler, and far faster, method produce accurate results?

    SELECT name [Table], sum(row_count) AS [Rows]

    FROM sys.dm_db_partition_stats WITH (NOLOCK), sysobjects WITH (NOLOCK)

    WHERE index_id < 2-- Just grab index 0 (heap) or 1 (cluster)

    AND xtype = 'U'

    AND object_id = object_id('' + name + '')

    GROUP BY name

  • Nice to see I started a healthy debate! I'm going to bear this stuff in mind - I'm always looking for smarter-running code!

  • ron.mcdowell that is an awesome script. My initial testing shows it is significantly faster than my script and for all my tests it was accurate. Now I need to learn how/why it works 🙂


  • Thanks for the script.

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply