SQL计算数据库表占用的真实空间大小

   最近客户的数据库暴涨,一开始找不到原因,用sql查询表的空间大小,结果之前用的sql语句只能查询除了text,image外的字段大小.搞得一时间混乱不堪.后来咨询了大师们,找到用sp_spaceused这个系统函数可以查询表的真实大小,包含text等字段.sql如下:

declare @id            NVARCHAR(100)
create table #spt_space
(
    [name]            NVARCHAR(50) null,
    [rows]          int null,
    [reserved]       NVARCHAR(50) null,
    [data]         NVARCHAR(50) null,
    [index_size]        NVARCHAR(50) null,
    [unused]         NVARCHAR(50) null
)
 
set nocount on
 
declare c_tables cursor for
select name from sysobjects where xtype = 'U'
 
open c_tables fetch next from c_tables into @id
 
while @@fetch_status = 0
begin
    /* Code from sp_spaceused */
    insert into #spt_space ([name],[rows],reserved,data,index_size,unused)
    EXEC sp_spaceused @id
    fetch next from c_tables   into @id
 
end
SELECT * FROM(
SELECT *,CAST(REPLACE(reserved,'KB','') AS INT) AS reservedindex FROM #spt_space
) c
order by c.reservedindex desc
 
drop table #spt_space
close c_tables
deallocate c_tables
posted @   温景良(Jason)  Views(3126)  Comments(0Edit  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
历史上的今天:
2010-07-01 判断机器是否有安装excel
2010-07-01 ADO.NET使用事务出错的解决(MSDTC) <转>
点击右上角即可分享
微信分享提示