A daily query is rarely just a query. Somebody wants the result, so automating it means three jobs: run it at a fixed time, turn the result into a file people can open, and deliver that file to them. Most ways of doing this handle the first job well and leave the other two to you.
There are three common approaches. Which one fits depends on your database, on what you are allowed to change on the server, and on what the result has to look like when it arrives.
| Runs where | Needs | Output | ||
|---|---|---|---|---|
| The database’s own scheduler | On the database server | Admin rights from a DBA | CSV or text | Depends on the database |
| Task Scheduler + a script | Any Windows machine | Scripting, a stored password | CSV, or Excel with extra modules | You write it |
| AutoSQL | Any Windows machine | An ODBC connection | Excel (incl. templates), CSV, HTML, email body | Built in |
Option 1: the database’s own scheduler
Most databases can run a statement on a schedule themselves. SQL Server’s version, SQL Server Agent with Database Mail, is the most complete one, so it is the example here. If you have the rights to create jobs on it, this is the built-in route: Database Mail sends the email, and an Agent job runs it on a schedule.
Once Database Mail has a profile configured, this sends a query’s result as a CSV attachment:
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Reports',
@recipients = 'sales@example.com',
@subject = 'Open orders',
@query = 'SELECT OrderNo, Customer, Amount FROM Shop.dbo.Orders WHERE Status = ''OPEN''',
@attach_query_result_as_file = 1,
@query_attachment_filename = 'open-orders.csv',
@query_result_separator = ',';
Put that in a job step and give the job a daily schedule, in SSMS under SQL Server Agent > Jobs, or in T-SQL:
EXEC msdb.dbo.sp_add_job @job_name = 'Daily open orders';
EXEC msdb.dbo.sp_add_jobstep @job_name = 'Daily open orders', @step_name = 'Send',
@command = N'EXEC msdb.dbo.sp_send_dbmail ...';
EXEC msdb.dbo.sp_add_schedule @schedule_name = 'Daily 07:00',
@freq_type = 4, @freq_interval = 1,
@active_start_time = 070000;
EXEC msdb.dbo.sp_attach_schedule @job_name = 'Daily open orders', @schedule_name = 'Daily 07:00';
EXEC msdb.dbo.sp_add_jobserver @job_name = 'Daily open orders';
Where it stops working:
- It needs rights on the production server. Creating or changing a job
takes sysadmin, or Agent and Database Mail roles in
msdbthat a DBA has to grant. Most of the people who want the report don’t have them, so every new report, and every change to one, becomes a request to the DBA. - It runs on the database server itself, so a report is now part of the production configuration, and a mistake in it runs there too.
- Email depends on the database. MySQL’s Event Scheduler and PostgreSQL’s
pg_croncan run a statement on a schedule, but neither can send an email. Azure SQL Database has no Agent at all (see scheduling queries on Azure SQL Database). - The attachment is plain text with a
.csvname. Column widths, number formats and an Excel layout are not on offer, and long results can be cut off unless you also set@query_result_width.
Option 2: Windows Task Scheduler and a script
This works with any database you can reach from a Windows machine, and with any SQL Server edition. A PowerShell script runs the query and saves the result. Task Scheduler starts the script every day.
# daily-report.ps1 - needs the SqlServer module: Install-Module SqlServer
Invoke-Sqlcmd -ServerInstance 'db01' -Database 'Shop' `
-Query "SELECT OrderNo, Customer, Amount FROM dbo.Orders WHERE Status = 'OPEN'" |
Export-Csv -Path 'C:\Reports\open-orders.csv' -NoTypeInformation
schtasks /create /tn "Daily open orders" /sc daily /st 07:00 ^
/tr "powershell -NoProfile -File C:\Reports\daily-report.ps1"
That covers running the query and saving a file. The rest is up to you:
- Email. PowerShell’s
Send-MailMessageis marked obsolete by Microsoft and doesn’t support the modern sign-in that Office 365 now expects. You end up with a third-party mail module or an SMTP relay, and a password stored somewhere the script can read it. - Excel.
Export-Csvwrites CSV. A real.xlsxneeds another community module, and putting results into an existing workbook with its formatting intact is real programming. - Other databases need their own driver and connection code.
- Upkeep. When the script breaks, the person who wrote it has to fix it. Often that person has moved on.
For one technical user with one report, this is a perfectly good answer. It gets harder to keep up as the number of reports, and of people asking for changes, grows.
Option 3: a tool that does all three
This is the gap AutoSQL was built for. It runs on any Windows machine, connects to any database with an ODBC driver (SQL Server, Azure SQL, MySQL, Oracle, PostgreSQL, Access and others), and handles the three jobs in one place:
- Run. It uses the Windows Task Scheduler, like option 2, but it sets the task up for you.
- Format. CSV, HTML or real Excel files, including writing into specific sheets and cells of an existing Excel template so formulas and layout survive.
- Deliver. Email with the result attached or in the message body, including Office 365 and Gmail accounts, or to a network folder or FTP server.
It needs no rights on the database server beyond the read access the query already uses, and no code.
A daily query that only speaks up when it matters
Bultsma Transport runs a query every day that lists any truck within 5,000 km of its next service. Most days nothing is due, and nobody gets an email. When a truck is due, the office receives the list as an Excel attachment. Once the service is booked, the truck drops out of the result and the emails stop on their own.
That is the pattern worth copying for any daily check: write the query to return no rows when all is well, so the daily email only arrives when someone has something to do. A report that turns up every day whether or not anything changed soon stops being read.
Setting up a daily query in AutoSQL
First create the action: a connection to your database, the query, and the output. Schedule a query in 3 steps walks through that. Then:
1. Test it
Click Run action to run the query, write the output and send the email once, exactly as the schedule will. If something is wrong, fix it here. With several actions, Run all tests them together.
A successful run confirms that the query ran, the output was written and the email was sent.
2. Create the daily schedule
Click Schedule, then Add new. AutoSQL creates the task in the Windows Task Scheduler for you.
In the New trigger dialog, choose Daily and the time it should run:
3. Decide who it runs as
The last screen names the task (by default the AutoSQL job file name plus the current time) and sets its security options. Choose Run whether user is logged on or not so the query also runs when nobody is signed in. Windows then asks for that account’s password once. That is standard Task Scheduler behaviour.
From now on the query runs every day at that time, writes the output and sends it, whether or not anyone is at their desk.
Which one should you use?
- SQL Server, you are the DBA or have the Agent rights, and CSV is fine: use Agent and Database Mail. It’s free and already installed.
- One report, you write scripts, and the output is simple: use Task Scheduler with PowerShell.
- No rights on the server, reports for people who don’t write code, Excel output people actually read, or a database other than SQL Server: that is what AutoSQL is for. Try it on the one query someone currently runs by hand.