SQL Server 查询数据库每张表的占用空间

 

 

具体

 

查询表占用空间的主要语句为 EXEC sp_spaceused @temp;

微软官方解释:

https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-spaceused-transact-sql?view=sql-server-ver15

 

 

--判断临时表是否存在,存在则删除重建
IF EXISTS ( SELECT  1
            FROM    tempdb..sysobjects
            WHERE   id = OBJECT_ID('tempdb..#tabName')
                    AND xtype = 'u' )
    DROP TABLE #tabName;
GO
CREATE TABLE #tabName
    (
     tabname VARCHAR(100)
    ,rowsNum VARCHAR(100)
    ,reserved VARCHAR(100)
    ,data VARCHAR(100)
    ,index_size VARCHAR(100)
    ,unused_size VARCHAR(100)
    );
 
DECLARE @name VARCHAR(100);
DECLARE @schemas VARCHAR(100);
DECLARE @temp VARCHAR(100);
DECLARE cur CURSOR
FOR
    SELECT  a.name
           ,s.name
    FROM    sys.objects a
           ,sys.schemas s
    WHERE   a.type = 'u'
            AND a.schema_id = s.schema_id
    ORDER BY a.name;
OPEN cur;
FETCH NEXT FROM cur INTO @name , @schemas;
WHILE @@fetch_status = 0
    BEGIN
        SET @temp = @schemas + '.[' + @name + ']';
        INSERT  INTO #tabName
                EXEC sp_spaceused @temp;
        PRINT @temp;
 
        FETCH NEXT FROM cur INTO @name , @schemas;
    END;
CLOSE cur;
DEALLOCATE cur;

SELECT  tabname AS '表名'
       ,rowsNum AS '表数据行数'
       ,reserved AS '保留大小'
       ,data AS '数据大小'
       ,index_size AS '索引大小'
       ,unused_size AS '未使用大小'
FROM    #tabName
ORDER BY CAST(ISNULL(rowsNum , 0) AS INT) DESC; 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值