How to check if stored procedure is already running?

  • I have stored procedure that I don't want 2 copies of it running at the same time.  How do I check if the stored procedure is already running in another instance? 

     

    I know that I could setup a table and just put a row in the table when it starts and empty it when I leave. 

     

    I want to know if there is a check that I can do on some system table that will tell me the same info.

     

    Thanks in advance for any responses to this post.   


    Live to Throw
    Throw to Live
    Will Summers

  • Will,

    Check this thread on the same subject.  I assume you mean "session" when you say "instance"?

    http://www.sqlservercentral.com/forums/shwmessage.aspx?forumid=8&messageid=114165

    Greg

    Greg

  • I have used application locks for this sort of proc. The idea is similar to using a table except everything is in memory. The outline code is:

    -- start of proc

    exec @err = sp_getapplock @Resource = N'YOURPROCNAME'

      ,@LockMode = N'Exclusive'

      ,@LockOwner = N'Session'

      ,@LockTimeout = 30000

    if (@err < 0)

    begin

     set @errorString = 'Failed to get exclusive lock.'

     goto onError

    end

    -- what you want to do...

     

    set @err = 0

    goto theEnd

    onError:

    raiserror(@errorString, 16, 1)

    theEnd:

    exec sp_releaseapplock @Resource = N'YOURPROCNAME'

        ,@LockOwner = N'Session'

    return @err

     

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply