Somebody on the net was looking for a way to retrieve info on all user tables in all databases in an instance. Here’s another 30-minute solution, addressing this:
create table tempdb.dbo.t (
serverName sysname null
,dbName sysname null
,schemaName sysname null
,name varchar(255)
,rows int not null
,reserved varchar(255) not null
,data varchar(255) not null
,index_size varchar(255) not null
,unused varchar(255) not null
,DateRun datetimeoffset not null default cast(current_timestamp as datetimeoffset)
)
go
exec master.dbo.sp_msforeachdb '
if db_id(''?'') > 4 begin
use [?];
declare @cmd varchar(max), @schema sysname;
declare c cursor local for
select sName = schema_name(schema_id)
,cmd = ''use [?]; exec sp_spaceused ''''''
+schema_name(schema_id) + ''.''
+name + '''''', true'' from sys.objects
where objectproperty(object_id, ''IsUserTable'') = 1
open c;
fetch next from c into @schema, @cmd
while @@fetch_status = 0 begin
insert tempdb.dbo.t (name, rows, reserved, data, index_size, unused) exec (@cmd);
update tempdb.dbo.t set
schemaName = @schema
,serverName = @@servername
,dbName = db_name()
where serverName is null and dbName is null and schemaName is null
fetch next from c into @schema, @cmd
end;
close c;
deallocate c;
end
'
select
FQName = serverName + '.' + dbName + '.' + schemaName + '.' + name
,RowsCount = cast(rows as bigint)
,ReservedMB = cast(replace(reserved, ' KB', '') as float) / 1024
,DataMB = cast(replace(data, ' KB', '') as float) / 1024
,IndexSizeMB = cast(replace(index_size, ' KB', '') as float) / 1024
,UnusedMB = cast(replace(unused, ' KB', '') as float) / 1024
from tempdb.dbo.t
go
select
serverName
,dbName
,ReservedMB = sum(cast(replace(reserved, ' KB', '') as float) / 1024)
,DataMB = sum(cast(replace(data, ' KB', '') as float) / 1024)
,IndexSizeMB = sum(cast(replace(index_size, ' KB', '') as float) / 1024)
,UnusedMB = sum(cast(replace(unused, ' KB', '') as float) / 1024)
from tempdb.dbo.t
group by
serverName
,dbName
go
drop table t
go