How to automatically run a stored procedure on scheduler basis?

后端 未结 3 344
终归单人心
终归单人心 2021-02-01 09:52

I want to execute a stored procedure automatically at every night. How can I do it. Please guide me with steps to achieve this target.

Thanks in advance.

3条回答
  •  盖世英雄少女心
    2021-02-01 10:23

    Try this:

    CREATE PROCEDURE MyTask
     AS
    BEGIN  
        SET NOCOUNT ON;
        --  For executing the stored procedure at 11:00 P.M
        declare @delayTime nvarchar(50)
        set @delayTime = '23:00'
    
        while 1 = 1
        begin
            waitfor time @delayTime 
            begin
                --Name for the stored proceduce you want to call on regular bases
                execute [DatabaseName].[dbo].[StoredProcedureName];
            end
        end
    END
    

    Then,

    -- Sets stored procedure for automatic execution.
    sp_procoption    @ProcName = 'MyTask',
                    @OptionName = 'startup',
                    @OptionValue = 'on'
    

    Reference:

    sp_procoption (Transact-SQL)

    Sets or clears a stored procedure for automatic execution. A stored procedure that is set to automatic execution runs every time an instance of SQL Server is started.

    WaitFor

    Blocks the execution of a batch, stored procedure, or transaction until a specified time or time interval is reached, or a specified statement modifies or returns at least one row.

提交回复
热议问题