一个统计表每天的新增行数及新增存储空间的功能
程序员文章站
2023-11-30 11:06:16
使用文中提供的代码做一个统计表每天的新增行数及新增存储空间的功能
实现步骤如下:
1. 创建表
创建表,存储每天的表空间占用情况
create table...
使用文中提供的代码做一个统计表每天的新增行数及新增存储空间的功能
实现步骤如下:
1. 创建表
创建表,存储每天的表空间占用情况
create table [dbo].[t_rpt_table_spaceinfo]( [table_name] [sysname] not null, [record_date] [date] not null, [record_time] [time](7) not null, [rows_count] [bigint] null, [reserved] [bigint] null, [data_size] [bigint] null, [index_size] [bigint] null, [unused] [bigint] null, constraint [pk_t_rpt_table_spaceinfo] primary key clustered ( [table_name] asc, [record_date] asc, [record_time] asc ) )
2. 新建作业
新建作业,作业计划每天凌晨运行一次,每天记录表占用的空间情况,存储到上一步建立的表中
作业中执行的t-sql代码为:
set nocount on /*创建临时表,存放用户表的空间及数据行数信息*/ create table #tablespaceinfo ( nameinfo varchar(500) , rowsinfo bigint , reserved varchar(20) , datainfo varchar(20) , index_size varchar(20) , unused varchar(20) ) declare @tablename varchar(255); /*使用游标,循环得到表空间使用情况*/ declare info_cursor cursor for select '[' + [name] + ']' from sys.tables where type = 'u'; open info_cursor fetch next from info_cursor into @tablename while @@fetch_status = 0 begin insert into #tablespaceinfo exec sp_spaceused @tablename fetch next from info_cursor into @tablename end insert into t_rpt_table_spaceinfo (record_date, record_time, [table_name], [rows_count] , reserved, [data_size], index_size, unused) select convert(date,getdate()), convert(varchar(8),getdate(),114), nameinfo, rowsinfo ,cast(replace(reserved, 'kb', '') as bigint) ,cast(replace(datainfo, 'kb', '') as bigint) ,cast(replace(index_size, 'kb', '') as bigint) ,cast(replace(unused, 'kb', '') as bigint) from #tablespaceinfo close info_cursor deallocate info_cursor drop table [#tablespaceinfo]
3. 查询结果
连续的数据记录之间做比较,即可得到数据的增量变化情况
示例代码如下:
;with table_spaceinfo as ( select record_date, record_time, table_name, rows_count, reserved, data_size, index_size, unused ,row_number() over(partition by table_name order by record_date,record_time asc) as list_no from t_rpt_table_spaceinfo ) select _a.table_name as 表名,convert(varchar(20),_a.record_date)+' '+convert(varchar(8),_a.record_time)+'~~' +convert(varchar(20),_b.record_date)+' '+convert(varchar(8),_b.record_time) as [时间段范围] ,_b.rows_count-_a.rows_count as [新增的行数] ,_b.data_size - _a.data_size as [新增数据空间(kb)] from table_spaceinfo _a join table_spaceinfo _b on _a.table_name=_b.table_name and _a.list_no=_b.list_no-1 order by [时间段范围]