sp_spaceused - How to measure the size in GB in all the tables in SQL

后端 未结 4 1304
离开以前
离开以前 2021-02-09 01:18

Following the discussion in How to measure table size in GB in a table in SQL, I\'m looking for a solution to measure the space used by all the tables of a SQL Server individual

4条回答
  •  野的像风
    2021-02-09 01:26

    There are a couple of options here:

    sp_msforeachtable

    sp_msforeachtable 'exec sp_spaceused [?]'
    

    While sp_msforeachtable can be used for this is has a couple of limitations:

    • Firstly you end up with a result set for each table that is run, which is hard to work with
    • If you run it over too many tables then you hit the limit of result sets that SSMS will support (think this is usually around the 200 mark)

    Collated results

    With a little more work, we can collate all the results into a single data set, avoiding these limitations. The pattern of this solution is similar whenever there is a requirement to run a sproc a bunch of times with different parameters and to collate the results from those runs.

    --Get list of interesting tables
    declare @tables table(id int identity(1,1), name varchar(200))
    declare @tablename varchar(200)
    insert @tables
    select table_name from information_schema.tables where table_type = 'BASE TABLE'
    
    --Define table for results
    declare @info table(name varchar(200), rows bigint, reserved varchar(200), data varchar(200), index_size varchar(200), unused varchar(200))
    
    --Working vars
    declare @max int, @pos int
    select @max = count(1), @pos = 1 from @tables
    
    --Loop to get all results
    while @pos <= @max
    begin
    
        select @tablename = name from @tables where id = @pos
    
        insert @info
        exec sp_spaceused @tablename
    
        set @pos = @pos + 1
    end
    
    --return all results
    select * from @info
    

    I prefer to use variable tables for this, but a cursor/temp table can be used as well.

提交回复
热议问题