我可以让 SQL Server 每 n 秒调用一次存储过程吗? [英] Can I get SQL Server to call a stored proc every n seconds?

查看:32
本文介绍了我可以让 SQL Server 每 n 秒调用一次存储过程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个每 n 秒调用一次的存储过程,有没有办法在 SQL Server 中执行此操作而不依赖于单独的进程?

I wish to have a stored proc that is called every n seconds, is there a way to do this in SQL Server without depending on a separate process?

推荐答案

使用 计时器激活.没有外部进程,在集群或镜像故障转移后继续工作,即使在另一台机器上恢复后也继续工作,它也适用于 Express.

Use a timer and activation. No external process, continues to work after a clustering or mirroring failover, continues to work even after a restore on a different machine, and it works on Express too.

-- 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 Server 每 n 秒调用一次存储过程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆