I have to start cyclic process in a stored procedure and then have to stop it after some time (after 12-24 hours). Stored procedure's work should not be started twice. SQL Server client (caller) should not wait and should not get execution timeout. How it can be implemented?

CREATE PROC dbo.CyclingProcess


    .. how to start or stop process by external caller


    WHILE(1 = 1)

        EXEC mysp_WorkingProcedure -- some working process...
              @input1 = @input1
             ,@delay  = @delay output 

           WAITFOR DELAY @delay



I have to do some repeated work during long time. I have to start this process and stop it. Why stored procedure? I have to change some input parameters for [some work] and call it again after some delay. Maybe you know other more smart way to implement it. This cyclic process should work in database.


If you want the stored procedure to be invoked by one process only with no other concurrent callers, you'd use sp_getapplock. Note that you'd have to throw an error for a 2nd process (with a zero timeout) but you can swallow this with a BEGIN TRY/CATCH arrangement.

Then you'd release it when the stored proc finishes.

Note that this uses of a stored proc is basically wrong. You'd have SQL Server Agent running the stored proc every minute. You may want sp_getapplock to prevent manual execution too but SQL Server Agent won't allow overlapping calls for the same job.

Or trigger is with Alerts in SQL Agent or Service Broker queues. We don't have enough info: you've asked for help with your chosen code-level solution. We don't know the problem you're trying to solve

If this is a single unit of work, then you need a transaction, and a 12-24 hour transaction is plain wrong

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.