介绍
统计多个 SQL Server 实例上多个数据库的表大小、最后修改时间和行数,可以使用以下的 SQL 查询来获取这些信息。
脚本
示例脚本:
DECLARE @Query NVARCHAR(MAX)
-- 创建一个临时表用于存储结果
CREATE TABLE #TableSizes
(
DatabaseName NVARCHAR(255),
SchemaName NVARCHAR(255),
TableName NVARCHAR(255),
RowCount BIGINT,
TotalSpaceUsedMB DECIMAL(18,2),
LastModifiedDateTime DATETIME
)
-- 构建动态SQL查询
SET @Query = ''
-- 获取数据库列表
SELECT @Query = @Query +
'USE [' + name + ']; ' +
'INSERT INTO #TableSizes ' +
'SELECT ' + QUOTENAME(name, '''') + ' AS DatabaseName, ' +
'SCHEMA_NAME(schema_id) AS SchemaName, ' +
't.name AS TableName, ' +
'SUM(p.rows) AS RowCount, ' +
'CONVERT(DECIMAL(18,2), SUM(a.total_pages) * 8 / 1024.0) AS TotalSpaceUsedMB, ' +
'MAX(last_user_update) AS LastModifiedDateTime ' +
'FROM ' + QUOTENAME(name) + '.sys.tables t ' +
'INNER JOIN ' + QUOTENAME(name) + '.sys.indexes i ON t.object_id = i.object_id ' +
'INNER JOIN ' + QUOTENAME(name) + '.sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id ' +
'INNER JOIN ' + QUOTENAME(name) + '.sys.allocation_units a ON p.partition_id = a.container_id ' +
'WHERE t.is_ms_shipped = 0 ' +
'GROUP BY t.name, SCHEMA_NAME(schema_id); '
FROM sys.databases
WHERE database_id > 4 -- Exclude system databases
-- 执行查询
EXEC sp_executesql @Query
-- 查询结果
SELECT * FROM #TableSizes
-- 删除临时表
DROP TABLE #TableSizes
Ending