I will explain How to Schedule and Automate Database Backups in SQL Server Express edition in this article.
SQL Server Express is a free edition and is available with a number of restrictions. For example; Your database size should not exceed 10GB and there are restrictions, such as SQL Server Agent is disabled, Auto tasks are disabled. For more information about SQL Server editions, read following article.
SQL Server Agent provides automatic backup jobs, Maintenance tasks in Enterprise, Standard, etc. editions and run our jobs. Since we cannot use this in Express, we can provide automatic backup using Windows Scheduler.
Open Windows Task Scheduler and click New Scheduler Task and type Task name and other settings like following.
Specify Scheduler and when will it trigger in this step.
In this step, specify what the Task scheduler will run. We will trigger a file called BackupDB.bat and BackupDB.bat will call and run DailyBackup.sql
When the job is running, it takes backup at 02:00 every night and keeps 4 backups and purge backups older than 4 days as follows.
Contents of BackupDB.bat are like following.
echo off sqlcmd -S "INSTANCE_NAME" -i "C:\Backup\DailyBackup.sql" forfiles -p "C:\Backup" -s -m *.bak* /D -4 /C "cmd /c del @path"
Contents of DailyBackup.sql are like following.
DECLARE @pathName NVARCHAR(512) SET @pathName = 'C:\Backup\DB_BACKUP_' + replace(convert(varchar, getdate(),111),'/','') + replace(convert(varchar, getdate(),108),':','') + '.bak' BACKUP DATABASE DB_NAME TO DISK = @pathName WITH NOFORMAT, NOINIT, NAME = N'db_backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
Task scheduler is going to trigger BackupDB.bat file at night 02:00 . This file is also executing DailyBackup.sql. Job will take database backup and purge older backup in the SQL Server Express edition.