Tables size in mssql
To check size used by data and indexes You can use following script
SELECT
Col.Column_Name
,Col.Table_Name
,OBJECT_ID(Col.Table_Name) AS [object_id]
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab
,INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY'
AND [Col].Table_name='YOUR_TABLE_NAME'
or more complicated (with index size)
DECLARE @tname nvarchar(128) = ''
set nocount on
--creating temp tabele
IF EXISTS (select * from tempdb..sysobjects where name like '#tblinfos%')
DROP TABLE #tblinfos
CREATE TABLE #tblinfos(
[name] [nvarchar](128) NOT NULL,
[rows] [char](11) NOT NULL,
[reserved] [varchar](18) NOT NULL,
[data] [varchar](18) NOT NULL,
[index_size] [varchar](18) NOT NULL,
[unused] [varchar](18) NOT NULL
)
--cleaning table infos
TRUNCATE TABLE #tblinfos
DECLARE @name nvarchar(128)
--createing cursor
DECLARE tables CURSOR FOR SELECT name FROM dbo.sysobjects WHERE (OBJECTPROPERTY(id, N'IsUserTable') = 1) AND (uid = 1) AND (name like @tname + '%')
OPEN tables
FETCH NEXT FROM tables INTO @name
WHILE (@@FETCH_STATUS = 0)
BEGIN
INSERT INTO #tblinfos EXEC('sp_spaceused ''' + @name + '''')
FETCH NEXT FROM tables INTO @name
END
CLOSE tables
--deallocating cursor
DEALLOCATE tables
UPDATE #tblinfos SET
[reserved] = REPLACE([reserved],' KB',''),
[data] = REPLACE([data],' KB',''),
[index_size] = REPLACE([index_size],' KB','') ,
[unused] = REPLACE([unused],' KB','')
SELECT * FROM (
SELECT
[name],
convert(int,[rows]) as [rows],
round(convert(float,[reserved])/1024,2) as [reserved],
round(convert(float,[data])/1024,2) as [data],
round(convert(float,[index_size])/1024,2) as [index_size],
round(convert(float,[unused])/1024,2) as [unused]
FROM #tblinfos
UNION
SELECT
'SUM' as [name],
sum(convert(int,[rows])) as [rows],
sum(round(convert(float,[reserved])/1024,2)) as [reserved],
sum(round(convert(float,[data])/1024,2)) as [data],
sum(round(convert(float,[index_size])/1024,2)) as [index_size],
round(sum(convert(float,[unused])/1024),2) as [unused]
FROM #tblinfos
) as tbl
ORDER BY [reserved] DESC,[data] DESC, [name] ASC
--droping temp table
DROP TABLE #tblinfos
Comments
Comments are closed