Schedule T-SQL queries to run automatically and deliver results via file or email using SQL Server Agent.
Automating reports removes manual query runs, guarantees consistent delivery, and frees engineers for higher-value work.
Enable SQL Server Agent, grant msdb permissions, and create a mail profile if emailing results.
Use sp_add_job
to define the job, sp_add_jobstep
for the query, sp_add_schedule
for timing, then sp_add_jobserver
to activate it.
SELECT o.id, c.name, o.total_amount, o.order_date FROM Orders o JOIN Customers c ON c.id = o.customer_id WHERE o.order_date = CAST(GETDATE() AS DATE);
Call bcp
from a job step: bcp "EXEC dbo.usp_daily_sales" queryout C:\Reports\sales.csv -c -t, -S .-T
.
Add a PowerShell step: Send-MailMessage -From reports@shop.com -To finance@shop.com -Subject "Daily Sales" -Body "Attached" -Attachments C:\Reports\sales.csv -SmtpServer smtp.shop.com
Check job history in SSMS or query msdb.dbo.sysjobhistory
for run_status = 1.Set alerts for failures.
Store report logic in a stored procedure, use parameters for dates, log execution time, and keep schedules staggered to avoid resource spikes.
Pick SSRS for pixel-perfect layouts, interactive filtering, or user-driven subscriptions.
.
Yes. Add additional sp_add_jobstep
calls and set @on_success_action
to continue.
Include them in the @command
field: 'EXEC dbo.usp_daily_sales @StartDate = GETDATE()-1'
.