如何停止统计数据库无止境的增长

时间:2019-04-24 09:01:18

标签: sql-server

我们拥有Microsoft SQL Server 2012数据库,用于存储来自排队系统的统计数据。排队系统每10分钟向数据库发送一次统计信息,数据库大小每周大约增长1 GB。

我们不需要1年以上的数据。

我们创建了一个SQL脚本来删除旧数据。执行脚本后,数据库大小更大。

use statdb

-- Execute as stat user
-- The following three settings are used to control what will be used

-- Amount of days of stat data which should be kept
DECLARE @numberOfDaysToKeep int=365

-- If set to 1, also the aggregated data will be removed, otherwise only the events will be removed
DECLARE @DeleteAggregateData int = 1

-- If set to 1, also the hardware monitoring data will be removed.
DECLARE @DeleteAgentDcData int = 1

-- Do not change anything below this line
DECLARE @DeleteBeforeDate int = (SELECT id FROM stat.dim_date WHERE full_date > DATEADD(day,-1-@numberOfDaysToKeep,GETDATE()) AND full_date < DATEADD(day,0-@numberOfDaysToKeep,GETDATE()))

-- Remove CFM events
DELETE FROM stat.fact_visit_events where date_key < @DeleteBeforeDate
DELETE FROM stat.fact_sp_events where date_key < @DeleteBeforeDate
DELETE FROM stat.fact_staff_events where date_key < @DeleteBeforeDate

-- ...continue to delete from other tables

我们希望数据库大小保持恒定。 MS SQL Server是否使用可用空间(删除后)还是DB大小以与删除前相同的速度增长?

还是我需要在脚本后运行SHRINK? (基于其他讨论,不推荐)

1 个答案:

答案 0 :(得分:0)

您不提供信息,因为您的数据库处于完全恢复模式或简单恢复模式。当然,您必须缩小日志文件和数据文件。在SSMS中,您可以看到数据文件和日志文件有多少可用空间。请参见下图。

enter image description here

有一个使用T-SQL收缩数据文件和日志文件的选项。 进一步了解DBCC SHRINKFILE (Transact-SQL)