我想到的解决方案是每周运行一个作业,该作业将对数据库中的所有表运行sp_spaceused并将此数据保存在表中。如果每个表的大小差异大于..比如说..10%,我将运行dbcc cleantable。
我的遍历表大小的代码如下所示:
if OBJECT_ID ('tempdb.dbo.#temp') is not null
drop table #temp;
if OBJECT_ID ('dbo.BigTables') is not null
drop table dbo.BigTables;
go
CREATE TABLE [dbo].[BigTables] (
[table_name] [sysname] NOT NULL,
[row_count] [int] NULL,
[col_count] [int] NULL,
[data_size] [varchar](50) NULL,
[Date] [datetime] NOT NULL,
[DBName] [nvarchar](128) NULL
);
GO
CREATE TABLE #temp (
table_name sysname ,
row_count int,
reserved_size varchar(50),
data_size varchar(50),
index_size varchar(50),
unused_size varchar(50)
);
go
INSERT #temp
EXEC sp_msforeachtable 'sp_spaceused ''?'''
insert into dbo.BigTables
SELECT a.table_name,
a.row_count,
count(*) as col_count,
a.data_size,
getdate() as [Date],
'MY DB' as DBName
FROM #temp a
INNER JOIN information_schema.columns b
ON a.table_name collate database_default
= b.table_name collate database_default
GROUP BY a.table_name, a.row_count, a.data_size
ORDER BY CAST(Replace(a.data_size, ' KB', '') as integer) desc
DROP TABLE #temp;
Select * from dbo.BigTables;
现在,您只需要构建逻辑即可验证一周中尺寸的变化并将其调度。