Backups, integrity checks and index maintenance must run on a schedule without anybody remembering to click. In SQL Server that is the job of SQL Server Agent. The most important part is not the schedule but the alert: a job that fails silently for three weeks is how data gets lost. This guide shows how to build a job in T-SQL and how to be notified when it fails.
Express edition has no SQL Server Agent. If you run Express, skip to the last section for a Windows Task Scheduler alternative.
Step 1: Make sure SQL Server Agent is running
In SQL Server Configuration Manager, check that the SQL Server Agent service is running and its start mode is Automatic, otherwise no job runs after the next reboot. In SSMS the Agent node under the server must show a green icon.
Step 2: Create a job with a step and a schedule
This example creates a nightly full backup at 02:00. Run it in a query window connected to the instance:
USE msdb;
GO
EXEC dbo.sp_add_job
@job_name = N'Nightly full backup - SalesDB',
@enabled = 1,
@description = N'Full backup of SalesDB every night at 02:00';
EXEC dbo.sp_add_jobstep
@job_name = N'Nightly full backup - SalesDB',
@step_name = N'Backup SalesDB',
@subsystem = N'TSQL',
@database_name = N'master',
@command = N'BACKUP DATABASE SalesDB
TO DISK = N''D:\Backups\SalesDB_nightly.bak''
WITH INIT, COMPRESSION, CHECKSUM;';
EXEC dbo.sp_add_schedule
@schedule_name = N'Every day at 02:00',
@freq_type = 4, -- daily
@freq_interval = 1, -- every 1 day
@active_start_time = 020000; -- HHMMSS
EXEC dbo.sp_attach_schedule
@job_name = N'Nightly full backup - SalesDB',
@schedule_name = N'Every day at 02:00';
EXEC dbo.sp_add_jobserver
@job_name = N'Nightly full backup - SalesDB';
The last line (sp_add_jobserver) is easy to forget: without it the job exists but is not assigned to any server and never runs. Prefer the same pattern with a dated file name in real life, so each night’s backup is kept (the backup and restore guide explains the options).
Test the job immediately instead of waiting for tonight:
EXEC msdb.dbo.sp_start_job @job_name = N'Nightly full backup - SalesDB';
Step 3: Set up Database Mail
Alerts need a way to send email. Enable the feature and create an account and a profile:
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'Database Mail XPs', 1; RECONFIGURE;
EXEC msdb.dbo.sysmail_add_account_sp
@account_name = N'SQL Alerts',
@email_address = N'alerts@example.com',
@display_name = N'SQL Server',
@mailserver_name = N'smtp.example.com',
@port = 587,
@enable_ssl = 1,
@username = N'alerts@example.com',
@password = N'your-smtp-password';
EXEC msdb.dbo.sysmail_add_profile_sp
@profile_name = N'DBA Mail';
EXEC msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = N'DBA Mail',
@account_name = N'SQL Alerts',
@sequence_number = 1;
Send a test message:
EXEC msdb.dbo.sp_send_dbmail
@profile_name = N'DBA Mail',
@recipients = N'dba@example.com',
@subject = N'Test from SQL Server',
@body = N'Database Mail works.';
If nothing arrives, look at SELECT * FROM msdb.dbo.sysmail_event_log ORDER BY log_id DESC;, which says why (wrong SMTP port, authentication refused, TLS…).
Finally tell the Agent to use the profile: in SSMS right-click SQL Server Agent, choose Properties, open Alert System, tick Enable mail profile, select DBA Mail and restart the Agent service.
Step 4: Create an operator and attach it to the job
An operator is the person (or mailbox) to notify:
EXEC msdb.dbo.sp_add_operator
@name = N'DBA team',
@enabled = 1,
@email_address = N'dba@example.com';
EXEC msdb.dbo.sp_update_job
@job_name = N'Nightly full backup - SalesDB',
@notify_level_email = 2, -- 2 = when the job fails
@notify_email_operator_name = N'DBA team';
The notify levels are 0 (never), 1 (on success), 2 (on failure) and 3 (always). Use 2 for routine jobs so you only get email when something is wrong, which keeps the alerts meaningful.
Test the alert once by making the job fail on purpose (for example, a backup path that does not exist) and check that the email arrives. An alert you have never seen working is not an alert.
Step 5: Read job history
SELECT TOP 20
j.name,
msdb.dbo.agent_datetime(h.run_date, h.run_time) AS started,
CASE h.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry' WHEN 3 THEN 'Canceled' END AS result,
h.message
FROM msdb.dbo.sysjobhistory AS h
JOIN msdb.dbo.sysjobs AS j ON j.job_id = h.job_id
WHERE h.step_id = 0 -- 0 = the overall job outcome
ORDER BY h.instance_id DESC;
For the detail of a failure, remove the step_id = 0 filter and look at the failing step’s message.
A sensible set of jobs
| Job | How often |
|---|---|
| Full backup | Daily or weekly |
| Differential backup | Daily, if full backups are weekly |
| Transaction log backup (FULL recovery databases) | Every 15 minutes |
Integrity check: DBCC CHECKDB (N'SalesDB') WITH NO_INFOMSGS; |
Weekly |
| Index maintenance and statistics update | Weekly |
| Delete old backup files and old job history | Weekly |
Instead of writing everything yourself, many administrators use the free, widely trusted Maintenance Solution scripts by Ola Hallengren, which create these jobs with sensible defaults. Whatever you choose, attach the failure alert to every job.
On Express edition: Task Scheduler and sqlcmd
Without the Agent, schedule the same T-SQL with Windows Task Scheduler using the sqlcmd tool. Create a task that runs daily with this action:
sqlcmd -S .\SQLEXPRESS -E -b -Q "BACKUP DATABASE SalesDB TO DISK = N'D:\Backups\SalesDB.bak' WITH INIT, CHECKSUM"
-E uses Windows authentication and -b makes sqlcmd return an error code when the statement fails. In Task Scheduler’s task settings, enable the option to notify or run an action on failure, or wrap the command in a small script that emails you when the exit code is not zero.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
