Scheduled run of stored procedure on SQL server
Asked Answered
H

8

67

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

Hendren answered 13/11, 2008 at 14:25 Comment(0)
M
116

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.

Morrissette answered 13/11, 2008 at 14:28 Comment(2)
So strange to me that this answer has gotten more upvotes in the last year than in the time between 2008 - 2013. Why is that?Morrissette
Well, I ended up here today due to a project requirement - and voila! another upvote for you!Coats
M
43

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:

Mucker answered 20/11, 2009 at 9:49 Comment(2)
is this a never ending process, an infinite loop ? is this will execute everyday at '03:33:33' ?Australorp
Use the following for a task that is run on a repeated interval (ideally add a check to prevent overlap such as via a monitoring table bit column [IsRunning]): waitfor delay '00:05'Silverpoint
Q
18

Yes, if you use the SQL Server Agent.

Open your Enterprise Manager, and go to the Management folder under the SQL Server instance you are interested in. There you will see the SQL Server Agent, and underneath that you will see a Jobs section.

Here you can create a new job and you will see a list of steps you will need to create. When you create a new step, you can specify the step to actually run a stored procedure (type TSQL Script). Choose the database, and then for the command section put in something like:

exec MyStoredProcedure

That's the overview, post back here if you need any further advice.

[I actually thought I might get in first on this one, boy was I wrong :)]

Quant answered 13/11, 2008 at 14:35 Comment(0)
S
15

Probably not the answer you are looking for, but I find it more useful to simply use Windows Server Task Scheduler

You can use directly the command sqlcmd.exe -S "." -d YourDataBase -Q "exec SP_YourJob"

Or even create a .bat file. So you can even 2x click on the task on demand.

This has also been approached in this HERE

Standpoint answered 7/3, 2014 at 19:29 Comment(0)
P
7

I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:

  1. We have some console programs that need to run every night as well. This way all scheduled tasks can be in one place. Of course, this creates a single point of failure, but if the console jobs don't run we're gonna lose a day's work the next day anyway.
  2. The program that kicks off the jobs captures print messages and errors from the server and writes them to a common application log for all our batch processes. It makes logging from withing the sql jobs much simpler.
  3. If we ever need to upgrade the server (and we are hoping to do this soon) we don't need to worry about moving the jobs over. Just re-point the application once.

It's a real short VB.Net app: I can post code if any one is interested.

Ptolemy answered 13/11, 2008 at 14:39 Comment(1)
No, I don't need the code, only general idea. Many thanks. :)Hendren
K
7

You could use SQL Server Service Broker to create custom made mechanism.

Idea (simplified):

  1. Write a stored procedure/trigger that begins a conversation (BEGIN DIALOG) as loopback (FROM my_service TO my_service) - get conversation handler

    DECLARE @dialog UNIQUEIDENTIFIER;
    
    BEGIN DIALOG CONVERSATION @dialog
            FROM SERVICE   [name] 
            TO SERVICE      'name' 
            ...;
    
  2. Start the conversation timer

    DECLARE @time INT;
    BEGIN CONVERSATION TIMER (@dialog)  TIMEOUT = @time;
    
  3. After specified number of seconds a message will be sent to a service. It will be enqueued with associated queue.

    CREATE QUEUE queue_name WITH STATUS = ON, RETENTION = OFF
                 , ACTIVATION (STATUS = ON, PROCEDURE_NAME = <procedure_name>
                 , MAX_QUEUE_READERS = 20, EXECUTE AS N'dbo')
                  , POISON_MESSAGE_HANDLING (STATUS = ON) 
    
  4. Procedure will execute specific code and reanable timer to fire again.


You can find fully-baked solution(T-SQL) written by Michał Gołoś called Task Scheduler

Key points from blog:

Pros:

  • Supported on each version (from Express to Enterprise). SQL Server Agent Job is not available for SQL Server Express
  • Scoped to database level. You could easiliy move database with associated tasks (especially when you have to move around 100 jobs from one enviromnent to another)
  • Lower privileges needed to see/manipulate tasks(database level)

Proposed distinction:

SQL Server Agent (maintenance):

  • backups
  • index/statistics rebuilds
  • replication

Task Scheduler (business processes):

  • removing old data
  • preaggregations/cyclic recalculations
  • denormalization

How to set it up:

  • get source code from section: "Do pobrania" - To download (enabling broker/setting up schema tsks/configuration table + triggers + stored procedure)/setting up broker things)
  • set up configuration table [tsks].[tsksx_task_scheduler] to add new tasks (columns names are self-descriptive, sample task included)

Warning: Blog is written in Polish but associated source code is in English and it is easy to follow.

Warning 2: Before you use it, please make sure you have tested it on non-production environment.

Kidding answered 28/1, 2017 at 12:31 Comment(0)
E
4

Using Management Studio - you may create a Job (unter SQL Server Agent) One Job may include several Steps from T-SQL scripts up to SSIS Packages

Jeb was faster ;)

Ermelindaermengarde answered 13/11, 2008 at 14:28 Comment(0)
T
3

You should look at a job scheduled using the SQL Server Agent.

Terceira answered 13/11, 2008 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.