Today, I got a service request that our customer needs to know the total data size per table and data size per column.
I shared the following information with this customer.
SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
t.Name
DECLARE @ObjectTable sysname = 'Example'
DECLARE @Name sysname
DECLARE @Type INT
DECLARE @Total BIGINT = 0
DECLARE @SQL NVARCHAR(4000)
DECLARE @ParmDefinition nvarchar(100)= N'@Total BIGINT OUTPUT'
DECLARE vColumns CURSOR FOR
SELECT C.name,T.USER_TYPE_ID from sys.columns c
JOIN SYS.TYPES T
ON C.USER_TYPE_ID=T.USER_TYPE_ID
WHERE object_id=OBJECT_id(@ObjectTable)
ORDER BY 1;
OPEN vColumns
FETCH NEXT FROM vColumns
INTO @Name, @Type
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Total=0
SET @SQL = 'SELECT @Total = SUM(DATALENGTH(' + @Name + ')) FROM ' + @ObjectTable
EXECUTE sp_executesql @SQL,@ParmDefinition, @Total = @Total OUTPUT;
PRINT 'Size:' + CONVERT(CHAR(20),@Total) + '|Type ID:' + CONVERT(CHAR(5),@Type) + '|Column Name:'+ CONVERT(CHAR(128), @Name) + '|SQL:' + @SQL
FETCH NEXT FROM vColumns INTO @Name, @Type
END
CLOSE vColumns;
DEALLOCATE vColumns;
Enjoy!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.