SqlServer 作业计时执行存储过程,杀超时进程

IF(1=0) --开启1,关闭0
    BEGIN
        create table #tmp(id int IDENTITY (1,1) not null, spid varchar(20), tableName varchar(200), startTime datetime)
        insert into #tmp select request_session_id spid, OBJECT_NAME(resource_associated_entity_id) tableName, er.start_time startTime    from sys.dm_tran_locks lk, sys.dm_exec_requests er where lk.request_session_id=er.session_id and lk.resource_type='OBJECT'

        Declare @str NVarchar(4000) --存查询语句
        Declare @spid Varchar(500)    --进程号
        Declare @tableName Varchar(200)
        Declare @startTime datetime --开始时间
        Declare @count int            --总记录数      
        Declare @i int
        Set @i = 0 
        Select @Count = Count(1) from #tmp
        While @i < @Count 
            Begin
               Set @str = 'select top 1 @spid = spid,@tableName=tableName,@startTime=startTime from #tmp where id not in (select top ' + Str(@i) + 'id from #tmp)'
               Exec Sp_ExecuteSql @str,N'@spid Varchar(20) OutPut, @tableName Varchar(200) OutPut, @startTime DateTime OutPut',@spid Output,@tableName Output,@startTime Output

                 if ((GETDATE() - @startTime) > '1900-01-01 00:00:15.000' and @tableName is not NULL)
                 begin
                    declare @sql varchar(1000)
                    set @sql='kill '+cast(@spid as varchar)
                    exec(@sql)
                    
                    Select '已杀进程:',@spid,@tableName,@startTime,@i,@Count,(GETDATE() - @startTime) --一行一行显示出来
                 end
               Set @i = @i + 1
            End
        drop table #tmp
    END

启动作业 循环执行存储过程,存储过程代码如上。
效果:10秒执行一次存储过程,杀掉持续15秒的进程

猜你喜欢

转载自www.cnblogs.com/mapstar/p/13186990.html