Home Forums SQL Server 2008 T-SQL (SS2K8) Possible to use tored proc to kill all queries running longer than 2 hours AND are blocking other queries RE: Possible to use tored proc to kill all queries running longer than 2 hours AND are blocking other queries

  • I totally Agree with Gail on that it will be total waste of resource if you do such kind of stuff. But if you really want to do that, you can use something like below.

    --

    Create PROC KillLongRunningQuery(

    @DBID int,

    @WaitTime bigint)

    as

    --exec KillLongRunningQuery 5,20000000

    DECLARE scursor CURSOR FAST_FORWARD FOR

    SELECT SPID

    FROM MASTER..sysprocesses WHERE waittime> @WaitTime--Specify time in

    and DBID = @DBID -- pass your DBID

    and spid > 50

    ORDER BY SPID

    DECLARE @SPID int

    OPEN scursor;

    FETCH NEXT FROM scursor INTO @SPID

    WHILE @@fetch_status = 0

    BEGIN

    DECLARE @StrSQL as varchar(200)

    SET @StrSQL= 'Kill ' + convert (char(4),@SPID )

    EXEC ( @StrSQL)

    FETCH NEXT FROM scursor INTO @SPID

    END

    CLOSE scursor;

    DEALLOCATE scursor;