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

前端 未结 11 1492
野的像风
野的像风 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.
    0 讨论(0)
  • 2020-11-28 08:50

    Since another similar question was asked, and will likely be closed as a duplicate of this one, and there are many options not mentioned in the answers already present here...

    Since you are using SQL Express you can't use SQL Server Agent. However there are many alternatives, all of which you can schedule using AT or Windows Task Scheduler depending on your operating system:

    • VBScript
    • C# command line app
    • batch file with SQLCMD
    • PowerShell

    All of these languages/tools (and many others) have the capacity to connect to SQL Server and execute a stored procedure. You can also try these Agent replacements:

    • SQLScheduler
    • Express Agent
    • Standalone SQL Agent (beta)
    0 讨论(0)
  • 2020-11-28 08:51

    The easiest way I have found to tackle this issue is to create a query that executes the stored procedure then save it. The query should look similar to this one below.

         use [database name]
         exec storedproc.sql
    

    Then create a batch file with something similar to the code below in it.

    sqlcmd -S servername\SQLExpress -i c:\expressmaint.sql
    

    Then have the task scheduler execute the batch as often as you like

    0 讨论(0)
  • 2020-11-28 08:51

    As you have correctly noted, without the agent process, you will need something else external to the server, perhaps a service you write and install or Windows scheduler.

    Note that with an Express installation for a local application, it is possible that the machine may not be on at the time you want to truncate the table (say you set it to truncate every night at midnight, but the user never has his machine on).

    So your scheduled task is never run and your audit log gets out of control (this is a problem with SQL Server Agent as well, but one would assume that a real server would be running non-stop). A better strategy if this situation fits yours might be to have the application do it on demand when it detects that it has been more than X days since truncation or whatever your operation is.

    Another thing to look at is if you are talking about a Web Application, there might be time when the application is loaded, and the operation could be done when that event fires.

    As mentioned in the comment, there is sp_procoption - this could allow your SP to run each time the engine is started - the drawbacks with this method are that for long-running instances, there might be a long time between calls, and it still has issues if the engine is not running at the times you need the operation to be done.

    0 讨论(0)
  • 2020-11-28 08:56

    Create a scheduled task that calls "C:\YourDirNameHere\TaskScript.vbs" on startup. VBScript should perform repeated task execution (in this example, it's a 15 minute loop)

    Via command line (must run cmd.exe as administrator):

    schtasks.exe /create /tn "TaskNameHere" /tr "\"C:\YourDirNameHere\TaskScript.vbs\" " /sc ONSTARTUP
    

    Example TaskScript.vbs: This executes your custom SQL script silently using RunSQLScript.bat

    Do While 1
        WScript.Sleep(60000*15)
        Set WshShell = CreateObject("WScript.Shell")
        WshShell.RUN "cmd /c C:\YourDirNameHere\RunSQLScript.bat C:\YourDirNameHere\Some_TSQL_Script.sql", 0
    Loop
    

    RunSQLScript.bat: This uses sqlcmd to call the database instance and execute the SQL script

    @echo off
    sqlcmd -S .\SQLEXPRESS -i %1
    
    0 讨论(0)
提交回复
热议问题