How to run a stored procedure every day in SQL Server Express Edition?

前端 未结 11 1510
野的像风
野的像风 2020-11-28 08:06

How is it possible to run a stored procedure at a particular time every day in SQL Server Express Edition?

Notes:

  • This is needed to truncate an audit t
11条回答
  •  臣服心动
    2020-11-28 08:50

    I found the following mechanism worked for me.

    USE Master
    GO
    
    IF  EXISTS( SELECT *
                FROM sys.objects
                WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')
                AND type in (N'P', N'PC'))
        DROP PROCEDURE [dbo].[MyBackgroundTask]
    GO
    
    CREATE PROCEDURE MyBackgroundTask
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
    
        -- The interval between cleanup attempts
        declare @timeToRun nvarchar(50)
        set @timeToRun = '03:33:33'
    
        while 1 = 1
        begin
            waitfor time @timeToRun
            begin
                execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];
            end
        end
    END
    GO
    
    -- Run the procedure when the master database starts.
    sp_procoption    @ProcName = 'MyBackgroundTask',
                    @OptionName = 'startup',
                    @OptionValue = 'on'
    GO
    

    Some notes:

    • It is worth writing an audit entry somewhere so that you can see that the query actually ran.
    • The server needs rebooting once to ensure that the script runs the first time.

提交回复
热议问题