[笔记] 查询表记录空间占用情况SQL脚本

USE ExpressDB

CREATE TABLE #tablespaceinfo
    (
      nameinfo VARCHAR(50) ,
      rowsinfo BIGINT ,
      reserved VARCHAR(20) ,
      datainfo VARCHAR(20) ,
      index_size VARCHAR(20) ,
      unused VARCHAR(20)
    )  
 
--创建游标

DECLARE Info_cursor CURSOR
FOR
    SELECT  [ + [name] + ]
    FROM    sys.tables
    WHERE   type = U;  
 
OPEN Info_cursor  

DECLARE @tablename VARCHAR(255);  
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  

 --创建临时表
CREATE TABLE [#tmptb]
    (
      TableName VARCHAR(50) ,
      DataInfo BIGINT , -- 以数据页大小为单位计算,即使表只有一条记录,也会占用一个数据页(8KB)
      RowsInfo BIGINT ,
      SpacePerRow  AS ( CASE RowsInfo
                         WHEN 0 THEN 0
                         --ELSE DataInfo / RowsInfo -- 数据页大小的信息除以记录数。
                         ELSE CAST(DataInfo AS decimal(8,2))/CAST(RowsInfo AS decimal(8,2))
                       END ) PERSISTED
    )

--插入数据到临时表
INSERT  INTO [#tmptb]
        ( [TableName] ,
          [DataInfo] ,
          [RowsInfo]
        )
        SELECT  [nameinfo] ,
                CAST(REPLACE([datainfo], KB, ‘‘) AS BIGINT) AS datainfo ,
                [rowsinfo]
        FROM    #tablespaceinfo
        ORDER BY CAST(REPLACE(reserved, KB, ‘‘) AS INT) DESC  


--汇总记录
SELECT  [tbspinfo].* ,
        [tmptb].[SpacePerRow] AS 每行记录大概占用空间(KB)
FROM    [#tablespaceinfo] AS tbspinfo ,
        [#tmptb] AS tmptb
WHERE   [tbspinfo].[nameinfo] = [tmptb].[TableName]
ORDER BY CAST(REPLACE([tbspinfo].[reserved], KB, ‘‘) AS INT) DESC  


DROP TABLE [#tablespaceinfo]
DROP TABLE [#tmptb]
View Code

当表的记录数少的时候,统计出来的每行记录占用空间是不准确的。

SELECT AVG(DATALENGTH(C0))+AVG(DATALENGTH(C1))+AVG(DATALENGTH(C2))+AVG(DATALENGTH(C3)) FROM [dbo].[TableName]
用统计字段大小方法计算结果较准确,但费时。

[笔记] 查询表记录空间占用情况SQL脚本,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。