开发者

Stopping long running stored procedure from script

开发者 https://www.devze.com 2023-04-12 01:04 出处:网络
I have a set of maintenance tasks in several databases that are triggered by a master stored procedure.The master stored procedure is started using sp_procoption to start on mssql startup.Then at a sp

I have a set of maintenance tasks in several databases that are triggered by a master stored procedure. The master stored procedure is started using sp_procoption to start on mssql startup. Then at a specified day and time, runs the child procedures in all of my databases.

I need to update this master script.

To clean up the update procedure, and not require stopping and restarting sql (to ensure that only one instance of the master procedure is running), I would like to be able to stop the stored procedure then restart it at the end of the update script. Restarting is not an issue, but does anyone know a way to stop the procedure from the update script?

Here is the script for my master scheduling proc:

USE master
GO
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'weekly_maintenance_task')
    DROP PROCEDURE weekly_maintenance_task
GO
CREATE PROCEDURE [dbo].[weekly_maintenance_task]
AS
BEGIN

    SET NOCOUNT ON
    DECLARE @timeToRun nvarchar(50)
    SET @timeToRun = '02:30:00'
    DECLARE @dayToRun nvarchar(10)
    SET @dayToRun = 'SUNDAY'


    WHILE 1 = 1
    BEGIN
        WAITFOR time @timeToRun
        BEGIN
            DECLARE @dayOfWeek NVARCHAR(10)
            SELECT @dayOfWeek = CASE DATEPART(weekday, GETDATE())
            WHEN 1 THEN 'SUNDAY'
            WHEN 2 THEN 'MONDAY'
            WHEN 3 THEN 'TUESDAY'
            WHEN 4 THEN 'WEDNESDAY'
            WHEN 5 THEN 'THURSDAY'
            WHEN 6 THEN 'FRIDAY'
            WHEN 7 THEN 'SATURDAY'
            END
            IF (@dayOfWeek = @dayToRun)
            BEGIN
                EXECUTE sp_msforeachdb 'USE ?
                IF DB_NAME() NOT IN (''master'', ''msdb'',''tempdb'',''model'')
                    IF EXISTS (select * from sys.procedures where name=''database_maintenance_weekly'')
                        EXECUTE database_maintenance_weekly'
            END
        END
    END
END

GO

sp_procoption @ProcName = 'weekly_maintenance_task',
              @OptionName = 'startup',
              @OptionValue = 'on'
开发者_StackOverflow中文版GO


You can use the kill command to kill a session. You can find the right session with dm_exec_requests and sys.fn_get_sql().

declare @nuke_spid int

select  @nuke_spid = session_id
from    sys.dm_exec_requests r 
outer apply sys.fn_get_sql(r.sql_handle) s
where   s.text like '%dm_exec_requests r%'

exec ('kill ' + @nuke_spid)

This should return Cannot use KILL to kill your own process.


Why run a stored procedure in an infinite loop? Just schedule a job to run your SPs at a specified date/time.

0

精彩评论

暂无评论...
验证码 换一张
取 消