25

How is it possible to run a stored procedure at a particular time every day in SQL Server Express Edition?

Notes:

  • This is needed to truncate an audit table
  • An alternative would be to modify the insert query but this is probably less efficient
  • SQL Server Express Edition does not have the SQL Server Agent

Related Questions:

Community
  • 1
  • 1
Thomas Bratt
  • 48,038
  • 36
  • 121
  • 139
  • This post looks interesting (referenced in an answer to one of the related questions): http://www.sqlteam.com/article/scheduling-jobs-in-sql-server-express – Thomas Bratt Nov 04 '09 at 17:42

11 Answers11

25

Since SQL Server express does not come with SQL Agent, you can use the Windows scheduler to run a SQLCMD with a stored proc or a SQL script.

http://msdn.microsoft.com/en-us/library/ms162773.aspx

Raj More
  • 47,048
  • 33
  • 131
  • 198
11

I found the following mechanism worked for me.

USE Master
GO

IF  EXISTS( SELECT *
            FROM sys.objects
            WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')
            AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[MyBackgroundTask]
GO

CREATE PROCEDURE MyBackgroundTask
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- The interval between cleanup attempts
    declare @timeToRun nvarchar(50)
    set @timeToRun = '03:33:33'

    while 1 = 1
    begin
        waitfor time @timeToRun
        begin
            execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];
        end
    end
END
GO

-- Run the procedure when the master database starts.
sp_procoption    @ProcName = 'MyBackgroundTask',
                @OptionName = 'startup',
                @OptionValue = 'on'
GO

Some notes:

  • It is worth writing an audit entry somewhere so that you can see that the query actually ran.
  • The server needs rebooting once to ensure that the script runs the first time.
Thomas Bratt
  • 48,038
  • 36
  • 121
  • 139
  • In conjunction with your audit trail, I would add to that stored proc a check of the process history, so that if it has not been run in 24 hours or whatever - to go ahead and run the process at startup. This would handle cases when the machine gets shut down over night or occasional nights or similar (a VM which is spun up on demand). – Cade Roux Nov 20 '09 at 14:46
  • Good point! For our case, the database runs continually as it is a customer system that is run 24x7. I wonder if the simplest thing to do is to run the 'MyDatabaseStoredProcedure' script before the wait? In our case this would work fine but it might not for a different application requirement. – Thomas Bratt Nov 26 '09 at 07:40
  • Are there any downsides to having a procedure running constantly in the background? – tufelkinder Jul 16 '14 at 18:59
  • Cons: 1. Have to create a new Stored Proc every time you need to schedule a job 2. Reboot on every schedule change – Raj More Sep 22 '14 at 15:45
  • You could get around having to reboot by creating a table with a running flag for each scheduled task. Set the flag at the top of the task's stored proc and use it in the while condition. Clearing the flag would cause it to stop after the current iteration completes. I'd also recommend having a table so you can store the last start time and duration for diagnostic purposes. – VoteCoffee Apr 15 '15 at 12:52
  • Procedure sp_procoption, Statement 'CONFIG' is not supported in this version of SQL Server. – Eng Soon Cheah Nov 28 '20 at 13:03
5

Create a scheduled task that calls "C:\YourDirNameHere\TaskScript.vbs" on startup. VBScript should perform repeated task execution (in this example, it's a 15 minute loop)

Via command line (must run cmd.exe as administrator):

schtasks.exe /create /tn "TaskNameHere" /tr "\"C:\YourDirNameHere\TaskScript.vbs\" " /sc ONSTARTUP

Example TaskScript.vbs: This executes your custom SQL script silently using RunSQLScript.bat

Do While 1
    WScript.Sleep(60000*15)
    Set WshShell = CreateObject("WScript.Shell")
    WshShell.RUN "cmd /c C:\YourDirNameHere\RunSQLScript.bat C:\YourDirNameHere\Some_TSQL_Script.sql", 0
Loop

RunSQLScript.bat: This uses sqlcmd to call the database instance and execute the SQL script

@echo off
sqlcmd -S .\SQLEXPRESS -i %1
VoteCoffee
  • 4,692
  • 1
  • 41
  • 44
  • I need to fix the task schedule command (via command line). It turns out it does not auto-restart on the next boot and I had to manually correct it. I will edit and fix the code later, just wanted people to be aware. The execution code works great though. – VoteCoffee Mar 10 '14 at 14:04
  • Still busy? Or do you have time to fix the command to make this answer complete? – Hugo Delsing Feb 24 '15 at 14:10
  • I figured out the setting I needed was advanced and not supported by schtask.exe. I instead opted to have the vbs perform the repeat functionality and set it to run at startup. It's good now. – VoteCoffee Feb 26 '15 at 22:41
4

If you are using Express Edition, you will need to use the Windows Scheduler or the application connecting to the server in some way.

You would use the scheduler to run sqlcmd. Here are some instructions for getting the sqlcmd working with express edition.

Yishai
  • 90,445
  • 31
  • 189
  • 263
2

SQL Scheduler from http://www.lazycoding.com/products.aspx

  • Free and simple
  • Supports all versions of SQL Server 2000, 2005, and 2008
  • Supports unlimited SQL Server instances with an unlimited number of jobs.
  • Allows to easily schedule SQL Server maintenance tasks: backups, index rebuilds, integrity checks, etc.
  • Runs as Windows Service
  • Email notifications on job success and failure
Iman
  • 17,932
  • 6
  • 80
  • 90
1

Since another similar question was asked, and will likely be closed as a duplicate of this one, and there are many options not mentioned in the answers already present here...

Since you are using SQL Express you can't use SQL Server Agent. However there are many alternatives, all of which you can schedule using AT or Windows Task Scheduler depending on your operating system:

All of these languages/tools (and many others) have the capacity to connect to SQL Server and execute a stored procedure. You can also try these Agent replacements:

Community
  • 1
  • 1
Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
1

The easiest way I have found to tackle this issue is to create a query that executes the stored procedure then save it. The query should look similar to this one below.

     use [database name]
     exec storedproc.sql

Then create a batch file with something similar to the code below in it.

sqlcmd -S servername\SQLExpress -i c:\expressmaint.sql

Then have the task scheduler execute the batch as often as you like

BrianMichaels
  • 522
  • 1
  • 7
  • 16
1

Another approach to scheduling in SQL Express is to use Service Broker Conversation Timers. To run a stored procedure periodically, which you can use to bootstrap a custom scheduler.

See eg Scheduling Jobs in SQL Server Express

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
0

You could use Task Scheduler to fire a simple console app that would execute the Sql statement.

Craig Bart
  • 75
  • 4
0

As you have correctly noted, without the agent process, you will need something else external to the server, perhaps a service you write and install or Windows scheduler.

Note that with an Express installation for a local application, it is possible that the machine may not be on at the time you want to truncate the table (say you set it to truncate every night at midnight, but the user never has his machine on).

So your scheduled task is never run and your audit log gets out of control (this is a problem with SQL Server Agent as well, but one would assume that a real server would be running non-stop). A better strategy if this situation fits yours might be to have the application do it on demand when it detects that it has been more than X days since truncation or whatever your operation is.

Another thing to look at is if you are talking about a Web Application, there might be time when the application is loaded, and the operation could be done when that event fires.

As mentioned in the comment, there is sp_procoption - this could allow your SP to run each time the engine is started - the drawbacks with this method are that for long-running instances, there might be a long time between calls, and it still has issues if the engine is not running at the times you need the operation to be done.

Cade Roux
  • 88,164
  • 40
  • 182
  • 265
0

Our company also use SQLEXPRESS and there is no SQL Agent.

Since there is no marked answer as "right" and all the solutions are quite complex I'll share what I did there. May be its really bad, but it worked great to me.

I've chosen operations of Insertion (people do) to a table that got closely the same time range i needed and made a trigger "ON INSERT" that applies needed function.

KennyKivi
  • 8
  • 1
  • 4