Schedule queries in SQL Server by creating a SQL Server Agent job, defining the T-SQL step, attaching a recurrent schedule, and letting the agent execute it automatically.
Automated jobs free engineers from manual runs, ensure reports are up-to-date, and lower the risk of missed deadlines. SQL Server Agent handles fault-tolerant execution, logging, and alerting without extra code.
Open SQL Server Management Studio (SSMS), right-click the Agent node, and choose “Start.” On Express editions, Agent is unavailable; consider Windows Task Scheduler with sqlcmd instead.
Run sp_add_job
to register a new job with a clear name, e.g., Daily_Total_Sales
. Use enabled = 1
so it runs immediately after a schedule is attached.
sp_add_jobstep
stores the actual query. Keep business logic in a stored procedure—this shortens the job script and simplifies future edits.
sp_add_schedule
lets you set frequency (daily, weekly, monthly) and exact timing. A single schedule can be shared by many jobs.
Finally, link the schedule and the job with sp_attach_schedule
, then assign the job to a server via sp_add_jobserver
.
Keep job names descriptive, store heavy logic in stored procedures, capture historical run info with msdb.dbo.sysjobhistory
, and set notifications on failure via Database Mail.
Developers often forget to set enabled = 1
on schedules or run jobs under accounts lacking permissions. Always test with EXEC msdb..sp_start_job
after creation.
Express lacks SQL Server Agent. Use Windows Task Scheduler with sqlcmd or PowerShell to call your script on a timer.
Configure Database Mail, create an operator, and set the job’s Notifications tab to email the operator on failure or completion.
Stored procedures centralize logic, support versioning, and simplify job scripts. Only keep lightweight statements directly in job steps.