Tuesday, January 29, 2008

[Maint] List size of each table in a DB

One of the handiest pieces of code I've ever used (aside from sp_who_3, but that's another post).
Put this in Master. Call it from whatever DB you're in. It'll list the table name, how many rows it has, how much space the Data uses, how much space the Indexes use, and the create date.

I don't know where it came from, but I didn't write it.

Enjoy!
TBD


USE [master]
GO
/****** Object: StoredProcedure [dbo].[sp_helptb] Script Date: 01/29/2008 09:55:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROC [dbo].[sp_helptb]

AS

set NOCOUNT ON


IF EXISTS (SELECT * FROM tempdb..sysobjects where name like '#spaceused%' )
DROP TABLE #spaceused

IF EXISTS (SELECT * FROM tempdb..sysobjects where name like '#TableOrder%' )
DROP TABLE #TableOrder

Create Table #spaceused(
id int IDENTITY(1,1),
Row int,
DataSpaceUsed float,
IndexSpaceUsed float
)

Create Table #TableOrder(
id int IDENTITY(1,1),
TableName varchar(100)
)


DECLARE @TableName sysname
DECLARE @Owner sysname
DECLARE @FQTableName sysname
DECLARE @indid int
DECLARE cur_tblfetch CURSOR FOR
select sysusers.name, sysobjects.name
from sysobjects
inner join sysusers on sysobjects.uid = sysusers.uid
where xtype = 'U'
order by sysobjects.name

OPEN cur_tblfetch
FETCH NEXT FROM cur_tblfetch INTO @Owner, @TableName
WHILE @@FETCH_STATUS = 0
BEGIN

SET @FQTableName = @Owner + '.' + @TableName
Insert into #spaceused
exec sp_MStablespace @FQTableName
Insert into #TableOrder
select @TableName


FETCH NEXT FROM cur_tblfetch INTO @Owner, @TableName
END
CLOSE cur_tblfetch
DEALLOCATE cur_tblfetch


select TableName, Row, DataSpaceUsed/1024 DataSpaceUsed_MB, IndexSpaceUsed/1024 IndexSpaceUsed_MB, sysobjects.crdate AS CreateDate
from #TableOrder
JOIN
#spaceused
ON #spaceused.id = #TableOrder.id
JOIN
sysobjects ON sysobjects.name = #TableOrder.TableName
ORDER BY TableName

No comments: