1、如果只是查询数据库的大小的话,直接使用以下语句即可:
EXEC sp_spaceused
2、为了保证查询结果的实时性,推荐使用下面这个语句来确保统计数据是最新的:
EXEC sp_spaceused @updateusage = N'TRUE';
执行完毕后结果是两个表,第一个表中包含了基本的统计信息,第二个表示更加详细的数据占用情况。
3、查询各表的占用大小
SELECT db_name() as DbName,
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS 总共占用空间MB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 0
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
总共占用空间MB desc;
4、查询各表的大小–使用存储过程
-- =============================================
-- 描 述:更新查询数据库中各表的大小,结果存储到数据表中
-- =============================================
CREATE PROCEDURE [dbo].[sp_UpdateTableSpaceInfo]
AS
BEGIN
--查询是否存在结果存储表
IF NOT EXISTS (SELECT * FROM sysobjects where id = OBJECT_ID(N'temp_tableSpaceInfo') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
--不存在则创建
CREATE TABLE temp_tableSpaceInfo
(name NVARCHAR(128),
rows char(11),
reserved VARCHAR(18),
data VARCHAR(18),
index_size VARCHAR(18),
unused VARCHAR(18))
END
--清空数据表
DELETE FROM temp_tableSpaceInfo
--定义临时变量在遍历时存储表名称
DECLARE @tablename VARCHAR(255)
--使用游标读取数据库内所有表表名
DECLARE table_list_cursor CURSOR FOR
SELECT name FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsTable') = 1 AND name NOT LIKE N'#%%' ORDER BY name
--打开游标
OPEN table_list_cursor
--读取第一条数据
FETCH NEXT FROM table_list_cursor INTO @tablename
--遍历查询到的表名
WHILE @@FETCH_STATUS = 0
BEGIN
--检查当前表是否为用户表
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(@tablename) AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
--当前表则读取其信息插入到表格中
EXECUTE sp_executesql N'INSERT INTO temp_tableSpaceInfo EXEC sp_spaceused @tbname', N'@tbname varchar(255)', @tbname = @tablename
END
--读取下一条数据
FETCH NEXT FROM table_list_cursor INTO @tablename
END
--释放游标
CLOSE table_list_cursor
DEALLOCATE table_list_cursor
END
GO
用的时候,执行一下存储:
EXEC sp_UpdateTableSpaceInfo
SELECT * FROM temp_tableSpaceInfo