Skip to content

Instantly share code, notes, and snippets.

@andrijac
Created November 28, 2023 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrijac/2f8d066f791e64900b14b7e16c57bab8 to your computer and use it in GitHub Desktop.
Save andrijac/2f8d066f791e64900b14b7e16c57bab8 to your computer and use it in GitHub Desktop.
-- Declare a temporary table to store the counts
CREATE TABLE #RowCounts (
TableName NVARCHAR(256),
RowCount1 INT
);
-- Declare variables
DECLARE @TableName NVARCHAR(256);
DECLARE @Sql NVARCHAR(MAX);
DECLARE @RowCount INT;
-- Cursor to iterate through user-created tables
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG = DB_NAME();
-- Open cursor
OPEN TableCursor;
-- Fetch the first table
FETCH NEXT FROM TableCursor INTO @TableName;
-- Iterate through the tables
WHILE @@FETCH_STATUS = 0
BEGIN
-- Check if the table exists and is accessible
IF OBJECT_ID(@TableName) IS NOT NULL
BEGIN
-- Prepare the dynamic SQL to get the row count
SET @Sql = N'SELECT @RowCountOUT = COUNT(*) FROM ' + @TableName;
-- Execute the dynamic SQL
EXEC sp_executesql @Sql, N'@RowCountOUT INT OUTPUT', @RowCountOUT = @RowCount OUTPUT;
-- Insert the row count into the temporary table
INSERT INTO #RowCounts (TableName, RowCount1) VALUES (@TableName, @RowCount);
END
-- Fetch the next table
FETCH NEXT FROM TableCursor INTO @TableName;
END
-- Close and deallocate the cursor
CLOSE TableCursor;
DEALLOCATE TableCursor;
-- Select the results
SELECT * FROM #RowCounts;
-- Drop the temporary table
DROP TABLE #RowCounts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment