效能調優前快速掌握資料庫各表筆數、資料大小、索引大小、未使用空間,定位大表壓力來源。
DECLARE @tablespaceinfo TABLE (
name SYSNAME,
rows BIGINT,
reserved VARCHAR(100),
data VARCHAR(100),
index_size VARCHAR(100),
unused VARCHAR(100)
);
DECLARE @tablename VARCHAR(255);
DECLARE info_cursor CURSOR FOR
SELECT QUOTENAME(name) FROM sys.tables WHERE type = 'U';
OPEN info_cursor;
FETCH NEXT FROM info_cursor INTO @tablename;
WHILE @@FETCH_STATUS = 0 BEGIN
INSERT INTO @tablespaceinfo EXEC sp_spaceused @tablename;
FETCH NEXT FROM info_cursor INTO @tablename;
END
CLOSE info_cursor;
DEALLOCATE info_cursor;
SELECT * FROM @tablespaceinfo
ORDER BY CAST(REPLACE(reserved, 'KB', '') AS INT) DESC;
reserved:表保留總空間 (資料+索引+未用)。data:資料頁面空間。index_size:索引頁面空間。unused:已配置未使用空間。參考後續文章「SQL Server 如何查看所有資料庫所有表大小資訊」,使用 sp_MSforeachdb + sp_MSforeachtable 或雙層游標實現。

