INF: How to Determine Number of Rows of Every Table in Database

Last reviewed: November 7, 1997
Article ID: Q176426
The information in this article applies to:
  • Microsoft SQL Server, versions 6.0 and 6.5

SUMMARY

The following script will return the name and the number of rows in every user-defined table in a given database:

   USE pubs -- replace pubs with your database name

   SET NOCOUNT ON
   DECLARE tables_cursor CURSOR
      FOR
      SELECT name FROM sysobjects WHERE type = 'U'
   OPEN tables_cursor
   DECLARE @tablename varchar(30), @quote char(1)
   SELECT @quote = '"'

   FETCH NEXT FROM tables_cursor INTO @tablename
   WHILE (@@fetch_status <> -1)
   BEGIN
      EXEC ("Select " + @quote+"Rows in " + @tablename + " = "+
                  @quote + ", count(*) from "+  @tablename)
      FETCH NEXT FROM tables_cursor INTO @tablename
   END
   DEALLOCATE tables_cursor
   SET NOCOUNT OFF

MORE INFORMATION

Notice that the "select count(*)" statement on a large table can be time consuming. Also, for additional information on every table, see the command DBCC CHECKDB in SQL Server Books Online.


Additional query words: records
Keywords : SSrvGen kbprg
Version : Windows:6.0,6.5
Platform : WINDOWS
Issue type : kbhowto
Solution Type : kbcode


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: November 7, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.