To make anΒ auto-scheduled backup and clean (shrink or delete old data) a SQL Server database, you can useΒ SQL Server Agent Jobs (available in SQL Server Standard and above, or via SQL Server Express with aΒ Task Scheduler workaround). Here’s a step-by-step guide for both backup and cleanup using SQL Server Management Studio (SSMS).
π§ Prerequisites:
- SQL Server installed and running
- SQL Server Agent enabled (for Standard/Enterprise editions)
- SSMS installed
β PART 1: Auto-Schedule Backup using SQL Server Agent
Step 1: Open SQL Server Management Studio (SSMS)
- Connect to your SQL Server instance.
Step 2: Enable SQL Server Agent
- In Object Explorer, find SQL Server Agent.
- If it’s stopped, right-click > Start.
Step 3: Create a New Job
- Right-click on SQL Server Agent > New Job.
Step 4: Define Job Properties
- Name:
DailyDatabaseBackup - Owner:
sa(or your user) - Category:
[Uncategorized (Local)] - Description: Optional
Step 5: Create a Backup Job Step
- Go to Steps > New
- Step name:
BackupDatabase - Type:
Transact-SQL script (T-SQL) - Database:
<YourDatabaseName> - Command:
BACKUP DATABASE [YourDatabaseName]
TO DISK = N'C:\SQLBackups\YourDatabaseName.bak'
WITH FORMAT, INIT, NAME = 'Full Backup of YourDatabaseName';
- Click OK
Step 6: Schedule the Job
- Go to Schedules > New
- Name:
DailySchedule - Frequency: Daily
- Time: e.g., 2:00 AM
- Click OK
Step 7: Save and Enable the Job
- Click OK to save the job.
- Right-click on the job > Start Job at Step…
β PART 2: Auto-Cleanup Old Data (Optional Maintenance Step)
You can either shrink the database or delete/archive old data.
Option 1: Shrink the Database (not recommended frequently)
- Create a new job step:
- Step name:
ShrinkDatabase - Command:
DBCC SHRINKDATABASE ([YourDatabaseName]);
β οΈ Note: Frequent shrinking can cause fragmentation. Use with caution.
Option 2: Delete Old Records from a Table
- Add another job step:
- Step name:
CleanupOldData - Command:
DELETE FROM YourTable
WHERE DateCreated < DATEADD(month, -6, GETDATE());
π§ Adjust the table name and time frame as needed.
π‘οΈ Optional: Email Notifications (if Database Mail is configured)
- Go to the Notifications tab.
- Set: “When the job completes” > Send email to operator.
π‘ Alternative for SQL Server Express (No Agent)
SQL Server Express lacks SQL Server Agent. Use Windows Task Scheduler:
- Write your T-SQL backup/cleanup commands in a
.sqlfile. - Create a
.batfile:
sqlcmd -S .\SQLEXPRESS -i "C:\Path\YourScript.sql"
- Schedule the
.batfile in Task Scheduler:
- Trigger: Daily at 2:00 AM
- Action: Start a program > browse to
.batfile
π Sample Backup Folder Recommendation:
- Store backups in:
D:\SQLBackups\YourDatabaseName\YYYYMMDD.bak - Modify backup script to:
DECLARE @filename NVARCHAR(200)
SET @filename = 'D:\SQLBackups\YourDatabaseName_' + CONVERT(NVARCHAR, GETDATE(), 112) + '.bak'
BACKUP DATABASE [YourDatabaseName]
TO DISK = @filename
WITH FORMAT, INIT, NAME = 'Daily Backup';



