DECLARE @tableName NVARCHAR(MAX) DECLARE @sql NVARCHAR(MAX) = ''
CREATE TABLE #TempTable (TableName SYSNAME, RowCounts BIGINT)
-- 遍历所有用户表 DECLARE TableCursor CURSOR FOR SELECT t.NAME FROM sys.tables t WHERE t.is_ms_shipped = 0 -- 过滤掉系统表 AND t.name NOT LIKE 'sys%' -- 可选:过滤掉以'.sys'开头的系统表
OPEN TableCursor FETCH NEXT FROM TableCursor INTO @tableName
WHILE @@FETCH_STATUS = 0 BEGIN SET @sql = N'SELECT ''' + @tableName + ''', COUNT(1) AS RowCounts FROM ' + QUOTENAME(@tableName) INSERT INTO #TempTable EXEC sp_executesql @sql
FETCH NEXT FROM TableCursor INTO @tableName
END
CLOSE TableCursor DEALLOCATE TableCursor
-- 输出结果 SELECT TableName, RowCounts FROM #TempTable ORDER BY RowCounts DESC;
-- 清理临时表 DROP TABLE #TempTable;