Skip to content

Instantly share code, notes, and snippets.

@sergiogarciadev
Last active February 15, 2018 05:05
Show Gist options
  • Save sergiogarciadev/a1e0d710bc854da5eb78 to your computer and use it in GitHub Desktop.
Save sergiogarciadev/a1e0d710bc854da5eb78 to your computer and use it in GitHub Desktop.
Get the number of records for each table in the SQL Server database.
DECLARE @sql NVARCHAR(4000)
DECLARE @tableName VARCHAR(255);
CREATE TABLE #DatabaseTables (TableName VARCHAR (255), RecordCount INT);
DECLARE tables_cursor CURSOR FOR
SELECT name FROM sysobjects WHERE xtype = 'U' ORDER BY name
OPEN tables_cursor
FETCH NEXT FROM tables_cursor INTO @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'INSERT INTO #DatabaseTables (TableName, RecordCount) SELECT ''' + @tableName + ''', COUNT(1) FROM ' + @tableName;
EXEC (@sql)
FETCH NEXT FROM tables_cursor INTO @tableName
END
CLOSE tables_cursor;
DEALLOCATE tables_cursor;
SELECT TableName, RecordCount FROM #DatabaseTables
DROP TABLE #DatabaseTables
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment