Overview
To maintain a healthy database performance or if your database is experiencing slow response time due to heavy usage, we suggest to improve its performance behavior by adding a SQL Server scheduled job (i.e. automated task) that will defragment the database table indexes and reduce the size of the SQL log file to free up disk space.
Applies to
- SQL Server
Procedure
-
In the Object Explorer of the Sql Server Management Studio (SSMS), expand the SQL Server Agent section to add a new job.
-
Right-click on the
Jobsfolder and choose New job… -
Configure the new job’s General tab:
- Insert a representative name such as
Defrag and shrink log. - Leave the Owner and Category as-is.
- Insert a representative description, such as
Defrag the WorkflowGen database and shrink the WorkflowGen database log.
- Insert a representative name such as
-
After setting the general configuration, go to the Steps page and click New…
-
On the General tab:
- Give the step a name (e.g.
Launch defrag). - Leave the
Typevalue set toTransact-SQL script (T-SQL). - Leave
Run asempty. - Select the database you want the job to run on.
- Insert the following command:
DECLARE @TableName nvarchar(255), @SqlQuery nvarchar(max) SELECT @TableName = min(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' WHILE @TableName is not null BEGIN SET @SqlQuery='ALTER INDEX ALL ON [' + @TableName + '] REORGANIZE;' EXEC SP_EXECUTESQL @SqlQuery SELECT @TableName = min(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' and TABLE_NAME > @TableName END - Give the step a name (e.g.
-
On the Advanced tab:
- On success action select the Go to the next step option.
-
RetryandIntervalcan be set to0. - For
Failure action, selectQuit the job reporting. - The rest can be left empty.
-
On the Steps page, add a second step.
-
On the General tab:
- Give the step a name (
Shrink Log). - Leave
Typeset to Transact-SQL script (T-SQL). - Leave
Run asempty. - Select the database you want the job to run on.
- Insert the following command:
DBCC SHRINKFILE (WFGEN_Log, 1) - Give the step a name (
-
On the Advanced tab:
- For
Success action, select theQuit the job reporting successoption. -
RetryandIntervalcan be set to0. - For
Failure action, select theQuit the job reportingfailure. - The rest can be left empty.
- For
-
Go to the Schedules page and click New…, then configure as follows:
- Insert a representative name for this new schedule.
- Make sure the
Schedule typeis set toRecurringandEnabledis checked. - We recommend setting
FrequencytoDailyandRecurs everyto1to3days, depending on the usage volume of the database. (The higher the volume, the smaller the occurrence interval should be.) - We recommend setting
Daily frequencytoOccurs once ata time outside of business hours. - We recommend setting
DurationtoNo end date.
