Overview
This article covers on how to create SQL maintenance plan to trim down Logs and RequestLog tables then shrink the database.
Note: This can't be applied to SQL Express editions because SQL Server Agent is not available.
Review the state of OLM database
- View the Disk Usage by Top Tables report.

- A report similar to below will be displayed.

Enable Agent XPs if not yet enabled
- Execute below SQL script.
- sp_configure 'show advanced options', 1
- go
- reconfigure
- go
- sp_configure 'Agent XPs', 1
- go
- reconfigure
- go
- Start SQL Server Agent if not started by right clicking SQL Server Agent and click Start.

Create SQL Maintenance Plan
- Right click Maintenance Plans and select New Maintenance Plan…

- Type in a name for the maintenance plan.

- Double click Subplan_1, rename subplan and set a schedule.

- From Toolbox, drag Execute T-SQL Stement Task twice to Designer and Shrink Database Task once. Optionally, you can separate the tasks schedules by creating subplans for each task.

- Click the first task in designer then click the arrow below the object and drag to the next task to link. Do the same on the 2nd task to link to 3rd task.

In Designer, double click the first Execute T-SQL Stement Task and paste the SQL script. Replace the value of @LogsRetentionDays in the script which is currently set to 7 days.
- use OLM
- go
-
- begin try
- begin transaction
-
- declare @LogsRetentionDays int = 7
- declare @BatchSize int = 10000
-
- while exists (select top(@BatchSize) * from Logs where cast([TimeStamp] as Date) < cast((getdate() - @LogsRetentionDays) as Date))
- begin
- delete top(@BatchSize) from Logs where cast([TimeStamp] as Date) < cast((getdate() - @LogsRetentionDays) as Date)
- end
-
- if @@TRANCOUNT > 0
- commit
- end try
-
- begin catch
- if @@TRANCOUNT > 0
- rollback
-
- select ERROR_MESSAGE()
- end catch
- go
- Double click the next Execute T-SQL Stement Task and paste the SQL script. Replace the value of @RequestLogsRetentionDays in the script which is currently set to 30 days.
-

- use OLM
- go
-
- begin try
- begin transaction
-
- declare @RequestLogsRetentionDays int = 30
-
- exec sp_RequestDelete2 @RetentionDays=@RequestLogsRetentionDays
-
- if @@TRANCOUNT > 0
- commit
- end try
-
- begin catch
- if @@TRANCOUNT > 0
- rollback
-
- select ERROR_MESSAGE()
- end catch
- Finally, double click Shrink Database Task and specify OLM database. Optionally, you can set to ignore offline databases.

- Set below options as required.

- Save the maintenance plan.
Optionally, test the maintenance plan by executing the plan manually.


