Other: Obtaining Record Counts for all Tables

Other: Obtaining Record Counts for all Tables

The following script will count all records in all tables. 

  1. DECLARE
  2.     @TableRowCounts TABLE (
  3.             [TableName]                        VARCHAR(128),
  4.             [Action_Group]      INT,
  5.             [Incomplete]             INT,
  6.             [Complete]                INT,
  7.             [Total]                        INT
  8.       )
  9. ;
  10.   
  11. INSERT INTO
  12.     @TableRowCounts (
  13.             [TableName],
  14.             [Action_Group],
  15.             [Incomplete],
  16.             [Complete],
  17.             [Total]
  18.   )
  19.         EXEC sp_MSforeachtable '
  20. SELECT
  21.         ''?'' AS [TableName],
  22.         [Action_Group],
  23.         SUM(CASE WHEN Result_Id = '''' THEN 1 ELSE 0 END) AS [Incomplete],
  24.         SUM(CASE WHEN Result_Id = '''' THEN 0 ELSE 1 END) AS [Complete],
  25.         COUNT(*) as [Total]
  26. FROM ?
  27.         GROUP BY Action_Group
  28. ';
  29.  
  30. SELECT
  31.       Action_Group, TableName, Incomplete, Complete, Total
  32. FROM
  33.     @TableRowCounts
  34. WHERE 1=1
  35.         AND Total > 0
  36. ORDER BY
  37.         Action_Group,
  38.         [TableName]
  39.  
  40. GO