Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduled run of stored procedure on SQL server

Is it possible to set up somehow Microsoft SQL Server to run a stored procedure on regular basis?

like image 567
Alexander Prokofyev Avatar asked Nov 13 '08 14:11

Alexander Prokofyev


People also ask

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 you check if stored procedure is scheduled?

job_id = j. job_id AND s. command LIKE '%procedurename%' ); Using this approach you could list all your store procedures (by name) and then find all jobs (or steps to be more specific) that contain these store procedures.

How do I schedule a stored procedure in task scheduler?

You can use the administrative task scheduler to execute stored procedures at a specific time. You must first define a task for the stored procedure execution. Then, when the specified time or event occurs for the stored procedure to run, the administrative task scheduler calls the stored procedure.


2 Answers

Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.

like image 51
Jeb Avatar answered Oct 10 '22 22:10

Jeb


If MS SQL Server Express Edition is being used then SQL Server Agent is not available. I found the following worked for all editions:

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.
  • A related question is: How to run a stored procedure every day in SQL Server Express Edition?
like image 36
Thomas Bratt Avatar answered Oct 10 '22 22:10

Thomas Bratt