簡體   English   中英

我可以讓SQL Server每隔n秒調用一次存儲過程嗎?

[英]Can I get SQL Server to call a stored proc every n seconds?

我希望每隔n秒調用一次存儲過程,有沒有辦法在SQL Server中執行此操作而不依賴於單獨的進程?

使用計時器激活 沒有外部進程,在群集或鏡像故障轉移后繼續工作,即使在另一台計算機上進行還原后仍可繼續工作,並且它也適用於Express。

-- create a table to store the results of some dummy procedure
create table Activity (
    InvokeTime datetime not null default getdate()
    , data float not null);
go  

-- create a dummy procedure
create procedure createSomeActivity
as
begin
    insert into Activity (data) values (rand());
end
go

-- set up the queue for activation
create queue Timers;
create service Timers on queue Timers ([DEFAULT]);
go

-- the activated procedure
create procedure ActivatedTimers
as
begin
declare @mt sysname, @h uniqueidentifier;
begin transaction;
    receive top (1)
        @mt = message_type_name
        , @h = conversation_handle
        from Timers;

    if @@rowcount = 0
    begin
        commit transaction;
        return;
    end

    if @mt in (N'http://schemas.microsoft.com/SQL/ServiceBroker/Error'
        , N'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
    begin
        end conversation @h;
    end
    else if @mt = N'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer'
    begin
        exec createSomeActivity;
        -- set a new timer after 2s
        begin conversation timer (@h) timeout = 2;
    end
commit
end
go

-- attach the activated procedure to the queue
alter queue Timers with activation (
    status = on
    , max_queue_readers = 1
    , execute as owner
    , procedure_name = ActivatedTimers);
go  


-- seed a conversation to start activating every 2s
declare @h uniqueidentifier;
begin dialog conversation @h
    from service [Timers]
    to service N'Timers', N'current database'
    with encryption = off;
begin conversation timer (@h) timeout = 1;

-- wait 15 seconds
waitfor delay '00:00:15';

-- end the conversation, will stop activating
end conversation @h;
go

-- check that the procedure executed
select * from Activity;

您可以設置SQL代理作業 - 這可能是唯一的方法。

SQL Server代理SQL Server的一個組件 - 但在Express版本中不可用 - 它允許您自動執行某些任務,如數據庫維護等,但您也可以使用它每隔n秒調用存儲過程。

我曾經設置了一個連續運行的存儲過程,在它的末尾有一個帶有WAITFOR的循環。

  • WHILE條件取決於從簡單配置表中讀取的值。 如果該值設置為0,則退出循環並完成該過程。
  • 我在最后放了一個WAITFOR DELAY,因此無論處理給定的迭代花了多長時間,它都會等待XX秒直到它再次運行它。 (XX也設置在配置表中並從中讀取。)
  • 如果它必須以精確的間隔運行(例如,分鍾中的0,15,30和45秒),則可以在循環結束時計算相應的WATIFOR TIME值。
  • 最后,我每分鍾都有一個SQL代理作業調用的過程。 該作業將始終“正在運行”,表明該過程正在運行。 如果程序被殺或崩潰,該工作將在不超過1分鍾內啟動。 如果該過程被“關閉”,則該過程仍然會運行,但是包含該處理的WHILE循環不會進入,從而產生開銷nill。

我不太喜歡在我的數據庫中使用它,但它滿足了業務需求。

WAITFOR   
{  
    DELAY 'time_to_pass'   
  | TIME 'time_to_execute'   
  | [ ( receive_statement ) | ( get_conversation_group_statement ) ]   
    [ , TIMEOUT timeout ]  
} 

如果要保持SSMS查詢窗口打開:

While 1=1
Begin
exec "Procedure name here" ;
waitfor delay '00:00:15';
End

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM