• sql server查询数据库的大小和各数据表的大小


    查询出来的结果中各字段的详细说明参考MSDN资料:https://msdn.microsoft.com/zh-cn/library/ms188776.aspx

    如果只是查询数据库的大小的话,直接使用以下语句即可:

    EXEC sp_spaceused

    为了保证查询结果的实时性,推荐使用 @updateusage 参数来确保统计数据是最新的:

    EXEC sp_spaceused @updateusage = N'TRUE';

    执行完毕后结果是两个表,第一个表中包含了基本的统计信息,第二个表示更加详细的数据占用情况。

    如果想具体查询某个表的大小,加上表名即可:

    如果想要一次性的把数据库中所有的表的大小全部查询出来的话,参考下面的方法:

    -- =============================================
    -- Description:    更新查询数据库中各表的大小,结果存储到数据表中
    -- =============================================
    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 --最近一条FETCH语句的标志
        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

    OK,搞定!

  • 相关阅读:
    jquery、js调用iframe父窗口与子窗口元素的方法整理
    js中的各种宽高以及位置总结
    javascript call与apply关键字的作用
    javascript之window对象
    CSS3 3D立方体效果
    CSS3 3D transform变换
    JS查找字符串中出现次数最多的字符
    写一个函数将传入的字符串转换成驼峰表示法
    数组去重方法
    内核升级得一个模范
  • 原文地址:https://www.cnblogs.com/sky6699/p/10307885.html
Copyright © 2020-2023  润新知