我可以让SQL Server每隔n秒调用一次存储过程吗?

Ian*_*ose 14 sql-server

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

Rem*_*anu 20

使用计时器激活.没有外部进程,在群集或镜像故障转移后继续工作,即使在另一台计算机上进行还原后仍可继续工作,并且它也适用于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;
Run Code Online (Sandbox Code Playgroud)

  • Service Broker位是SQL Server引擎本身的一部分(不是可选安装).单个数据库可以禁用SSB,但默认情况下在除主服务器和模型之外的每个数据库中启用.它是否完全包含在DB中(没有msdb依赖项),因此它可以作为备份/还原到新主机.它可以在没有任何问题的情况下幸免于DB镜像故障转移,因为没有msdb依赖性.它比SQL Agent更好地扩展和执行*way*.它通过max_queue_readers具有自我负载平衡功能.激活是基于推送的,而不是拉动.在每个SQL Express中.这样的例子不胜枚举. (8认同)

mar*_*c_s 6

您可以设置SQL代理作业 - 这可能是唯一的方法.

SQL Server代理SQL Server的一个组件 - 但在Express版本中不可用 - 它允许您自动执行某些任务,如数据库维护等,但您也可以使用它每隔n秒调用存储过程.