SQL Server Get Azure SQL table size by month

gv8xihay  于 2023-05-16  发布在  其他
关注(0)|答案(1)|浏览(162)

I have Azure SQL DB and need to get size of each table by month wise. I have a query which will give entire size of tables, but how can I extract the size of table by month wise?

Query to get size of table:

SELECT 
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows,
SUM(a.total_pages) * 8 AS TotalSpaceKB, 
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS 
NUMERIC(36, 2)) AS TotalSpaceMB,
SUM(a.used_pages) * 8 AS UsedSpaceKB, 
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 
2)) AS UsedSpaceMB, 
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 
1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
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.NAME NOT LIKE 'dt%' 
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255 
GROUP BY 
t.Name, s.Name, p.Rows
ORDER BY 
TotalSpaceMB DESC, t.Name
hmmo2u0o

hmmo2u0o1#

I agree with Thom A and siggemannen The size of each table is partitioned by year and month, ordered by partition year, partition month, and table size in descending order I did research and followed the same approach the query gives size of each table by month wise.

I have queried to get the size of the tables.

SELECT 
    t.name AS table_name,
    SUM(a.total_pages) * 8 AS table_size_kb
FROM 
    sys.tables AS t
    INNER JOIN sys.indexes AS i ON t.object_id = i.object_id
    INNER JOIN sys.partitions AS p ON i.object_id = p.object_id AND i.index_id = p.index_id
    INNER JOIN sys.allocation_units AS a ON p.partition_id = a.container_id
GROUP BY 
    t.name
ORDER BY 
    table_size_kb DESC;

You can try this below query that partition_year and partition_month

SELECT
    t.name AS table_name,
    SUM(a.total_pages) * 8 AS table_size_kb,
    DATEPART(YEAR, p.partition_number) AS partition_year,
    DATEPART(MONTH, p.partition_number) AS partition_month
FROM
    sys.tables AS t
    INNER JOIN sys.indexes AS i ON t.object_id = i.object_id
    INNER JOIN sys.partitions AS p ON i.object_id = p.object_id AND i.index_id = p.index_id
    INNER JOIN sys.allocation_units AS a ON p.partition_id = a.container_id
GROUP BY
    t.name,
    DATEPART(YEAR, p.partition_number),
    DATEPART(MONTH, p.partition_number)
ORDER BY
    partition_year,
    partition_month,
    table_size_kb DESC;

相关问题