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
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:
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.