0

I have a stored procedure GenerateAttendance, execution time will take approx 3-4 min. Meanwhile my program requests the same stored procedure for execute.

I want to restrict my program from executing it if it's currently running. Is there any way, in SQL Server 2008 R2 Express, to find the stored procedure is currently executing or what, before requesting to execute it again.

I tried below option but it does not work for me

SELECT  OBJECT_NAME(@@PROCID) 
select OBJECT_SCHEMA_NAME(@@PROCID)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
gbbosmiya
  • 509
  • 8
  • 23

2 Answers2

0

There are 2 stored procedure that are used for this: sp_getapplock and sp_releaseapplock.

Modify the stored procedure in this way:

ALTER PROCEDURE GenerateAttendance  
AS
BEGIN
    -- Acquire lock
    DECLARE @result int
    EXEC @result = sp_getapplock @Resource = 'GenerateAttendance', @LockMode = 'Exclusive'
    IF @result NOT IN (0,1)
        RAISERROR ('Cannot acquire lock', 16, 1)

    BEGIN TRY
        -- Actual code of your SP here

    END TRY 
    BEGIN CATCH
        -- Release lock
        EXEC @result = sp_releaseapplock @Resource = 'GenerateAttendance'
        IF @result != 0
            PRINT 'Cannot release lock'
    END CATCH
END
GO
bjnr
  • 3,353
  • 1
  • 18
  • 32
  • thanks Dd2 i want it very simple if my sp is currently executing it will not allow me to execute again. how do i achieve this from above code – gbbosmiya Nov 20 '13 at 08:55
0

Added a simpler solution, as @gbbosmiya requested.

IF EXISTS(
    SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
    FROM
        sys.dm_exec_query_stats AS deqs
        CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
    WHERE dest.TEXT LIKE '%GenerateAttendance%'    
    ORDER BY deqs.last_execution_time DESC)
BEGIN
    PRINT 'This stored procedure is currently executing'
END
ELSE
BEGIN
-- Execute stored proc
END

GO
bjnr
  • 3,353
  • 1
  • 18
  • 32
  • it gives error: Msg 1033, Level 15, State 1, Line 7 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified. – gbbosmiya Nov 20 '13 at 09:06