sql server 查询所有表的记录条数

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;

 

2024-03-07 09:15:28【出处】:https://blog.csdn.net/wangqiaowq/article/details/135845632

=======================================================================================

也可以使用 :sp_spaceused 'dbo.T_test'; 的形式,

name rows reserved data index_size unused
T_test 12720443 16855592 KB 15996968 KB 840640 KB 17984 KB

 

posted on 2024-03-07 09:16  jack_Meng  阅读(136)  评论(0编辑  收藏  举报

导航