注意:生产环境请谨慎操作,建议先在测试环境进行测试验证。
数据库
----查询当前数据库大小
exec sp_spaceused
----批量查询所有数据库大小
with fs
as
(
select database_id, type, size * 8.0 / 1024 size
from sys.master_files
)
select
name,
(select cast(round(sum(size),2) as numeric(15,2)) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,
(select cast(round(sum(size),2) as numeric(15,2)) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB
from sys.databases db
order by 2 desc;
表格
----查询单个表格大小
exec sp_spaceused '【表名】'//将【表名】替换为需要查询表的名称
----批量查询数据库中各表的大小
方法一:
(注:亦适用于含多种架构表的数据库)
declare @table_spaceused table
(name nvarchar(100)
,rows int
,reserved nvarchar(100)
,data nvarchar(100)
,index_size nvarchar(100)
,unused nvarchar(100) )
insert into @table_spaceused
(name,rows,reserved,data,index_size,unused )
exec sp_MSforeachtable
@command1='exec sp_spaceused ''?'''
select * from @table_spaceused
sp_MSforeachtable使用方法可参考链接:sp_MSforeachtable使用方法可参考链接:文章链接
方法二:
(注:不适用于含多种架构表的数据库)
DECLARE @tablespaceinfo TABLE (
nameinfo VARCHAR(50),
rowsinfo INT,
reserved VARCHAR(20),
datainfo VARCHAR(20),
index_size VARCHAR(20),
unused VARCHAR(20)
)
DECLARE @tablename VARCHAR(255);
DECLARE Info_cursor CURSOR FOR
SELECT '['+[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
方法三:
(注:不适用于含多种架构表的数据库)
--列表输出
SET NOCOUNT ON
DECLARE @db VARCHAR(20)
--获取当前数据库
SET @db=db_name()
DBCC UPDATEUSAGE(@db) WITH NO_INFOMSGS
GO
--创建临时表
CREATE TABLE #tblSpace
(
数据表名称 varchar(250) null,
记录笔数 int null,
保留空间 varchar(15) null,
数据使用空间 varchar(15) null,
索引使用空间 varchar(15) null,
未使用空间 varchar(15) null
)
DECLARE @tblname varchar(250)
DECLARE curTbls CURSOR FOR
SELECT name FROM sysobjects
--BASE TABLE很重要
WHERE type='U'
OPEN CurTbls
FETCH NEXT FROM curTbls INTO @tblName
WHILE @@FETCH_STATUS=0
BEGIN
INSERT #tblSpace EXEC sp_spaceused @tblName
FETCH NEXT FROM curTbls INTO @tblName
END
CLOSE CurTbls
DEALLOCATE curTbls
SELECT * FROM #tblSpace ORDER BY 记录笔数 DESC
--删除表格
DROP TABLE #tblSpace