How to automatically run a stored procedure on scheduler basis?

后端 未结 3 342
终归单人心
终归单人心 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:21

    You can create a job with the SQL Server Agent.

    enter image description here

    Right-click on the Jobs folder to open the menu, select New Job:

    enter image description here

    When you create a new job a window will open and you will provide the details of you job that you want to create. Including:

    • Name - in the General tab
    • Steps - can run a SQL script, SSIS package, stored procedure
    • Schedule - recurring, weekly, daily, etc. at the frequency that you pick.

    Here is a Step by Step by Guide to creating a SQL Job

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 10:29

    Quick solution is,

    Create your stored procedure Write the SQL Job (below are the steps)

    http://www.dailycoding.com/Posts/step_by_step_guide_to_add_a_sql_job_in_sql_server_2005.aspx

    In Step 5 configure stored procedure that you created.

    0 讨论(0)
提交回复
热议问题