按日期记录的表的大小。

时间:2014-11-20 17:35:03

标签: sql sql-server sql-server-2008

是否可以在特定日期之前根据记录获取表格的大小。含义我想知道具有2年及更长记录的表的大小。

2 个答案:

答案 0 :(得分:1)

由于您希望仅根据表格中的部分行获得大小,您可以总结每列的长度,这将是近似的

假设您的日期列已创建日期

select SUM(datalength(col1))+SUM(datalength(col2))+.. from tableName
WHERE datediff(year, createdDate, getdate()) > 2

答案 1 :(得分:0)

您可以获取当前为该表分配的数据库页数,并将该值调整为2年前的行数:

select sq.SchemaName, sq.TableName, sq.IndexName, sq.IndexId, sq.Rows, sq.TableSize,
    sum(sq.total_pages) as [TotalPages],
    round(cast(sum(sq.total_pages) as money) / 128, 3) as [ObjectSizeMB]
from (  
    select object_schema_name(t.object_id) as [SchemaName], t.name as [TableName], i.Name as [IndexName], i.Index_Id as [IndexId], pt.Rows,
        au.total_pages,
        round(cast(sum(au.total_pages) over(partition by t.object_id) as money) / 128, 3) as [TableSize]
    from sys.tables t
        inner join sys.partitions pt on t.object_id = pt.object_id
        inner join sys.indexes i on pt.object_id = i.object_id and pt.index_id = i.index_id
        inner join sys.allocation_units au on au.container_id = case
            when au.type in (1, 3) then pt.hobt_id
            when au.type = 2 then pt.partition_id
        end
    where t.type in ('U', 'V')
    ) sq
where sq.IndexId < 2
group by sq.TableName, sq.IndexName, sq.IndexId, sq.Rows, sq.TableSize, sq.SchemaName
order by sq.tablesize desc, sq.SchemaName, sq.TableName, TotalPages desc;

ObjectSizeMB列显示对象占用的空间(堆,聚簇或非聚簇索引),而TableSize包含整个表(或索引视图)的这些值的小计。根据您对“表格大小”的定义,您可以使用其中任何一个。如果您想在列表中看到非聚集索引,则应注释掉外部where sq.IndexId < 2

应该给你一个很好的起点。