Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a stored procedure every day in SQL Server Express Edition?

Tags:

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:

  • How can I schedule a daily backup with SQl Server Express?
  • Scheduled run of stored procedure on SQL Server
like image 632
Thomas Bratt Avatar asked Nov 04 '09 17:11

Thomas Bratt


People also ask

How do I schedule a stored procedure to run in SQL Server?

Expand SQL Server Agent, expand Jobs, right-click the job that you want to schedule, and click Properties. Select the Schedules page, and then click Pick. Select the schedule that you want to attach, and then click OK.

Can we schedule stored procedure in SQL Server?

In SQL Server, the best way to schedule a stored procedure is by using the SQL Server Agent. But, the SQL Server Agent is not available in the SQL Server Express Edition. So, by using SQL Server Express, we cannot use the Agent service to schedule the execution of a stored procedure.

How do I automate a SQL query to run daily?

Click on the 'Schedule' menu on the left of the New Job window and enter the schedule information (e.g. daily and a time). Click 'OK' - and that should be it.


2 Answers

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

like image 81
Raj More Avatar answered Oct 18 '22 18:10

Raj More


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.
like image 26
Thomas Bratt Avatar answered Oct 18 '22 19:10

Thomas Bratt