【问题标题】:Run stored procedure from sql job based on select results根据选择结果从 sql 作业运行存储过程
【发布时间】:2015-09-09 08:12:36
【问题描述】:

我有一个包含四个字段a,b,c,d 和一个存储过程sp_x 的sql 表。

如何创建一个将定期运行并做两件事的作业(通过一个选择):

  1. 为具有b=1 的行更新字段c 和字段d

  2. 然后执行 sp_x 传递它字段 a 但仅适用于具有 b=1 的行

【问题讨论】:

  • “单选”为什么? 2个或更多有什么问题?实际目标是什么? (除了定期运行)
  • b 指示所有已过期的行(实际检查不是 b=1,而是实际上是 b
  • only on select 的原因是需要先更新,在字段 c 更新为取消状态后,select 不会再次选择它。
  • 您可以使用@EdwardComeau 在他的回答中提到的OUTPUT,或者您可以将AFTER UPDATE 触发器添加到记录您想要的事件的表中。

标签: sql-server stored-procedures sql-server-2008-r2 jobs


【解决方案1】:

您可以使用更新语句的“输出”来接收您刚刚更新的列的行 ID,并将此数据写入临时表或表变量。

这允许使用更多语句来处理日志记录活动。

您还可以考虑在您的表上使用 on update 触发器,当您的状态更改时执行日志记录。

use [tempdb];
go

create table [outputexample]
(
      [rowid] int identity(1,1)
    , [datetime] datetime default (getdate()) not null
    , [status] varchar(20) not null
);

insert into [outputexample] ([status])
select 'Active' union all
select 'Closed' union all
select 'Active'
go

预定工作代码:

declare @updatedrow table
(
    [rowid] int
);

update [outputexample]
set [datetime] = getdate()
    , [status] = 'Closed'
output inserted.[rowid]
into @updatedrow
where [datetime] < getdate()
    and [status] <> 'Closed';


declare @rowid int;

declare cursor_updatedrow cursor for
select [rowid] from @updatedrow;

open cursor_updatedrow;

fetch next from cursor_updatedrow into @rowid;

while @@fetch_status = 0
begin

    -- exec sp_myauditsp @rowid = @rowid
    print cast(@rowid as varchar(20)) + ' was updated to closed.'

    fetch next from cursor_updatedrow into @rowid;
end

close cursor_updatedrow;
deallocate cursor_updatedrow;

【讨论】:

    【解决方案2】:

    更新你想要的行:

    UPDATE mytable SET C=..., D=... WHERE B=1
    

    仅对某些行执行存储过程:

    DECLARE @a int
    DECLARE my_cursor CURSOR
    FOR SELECT a FROM jobtable WHERE b=1
    OPEN my_cursor
    FETCH NEXT FROM my_cursor INTO @a
    WHILE @@FETCH_STATUS=0
    BEGIN 
      EXEC sp_x @a
    END
    FETCH NEXT FROM my_cursor into @a
    CLOSE my_cursor
    DEALLOCATE my_Cursor
    

    所有内容都在您想要运行的作业中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2022-01-08
      相关资源
      最近更新 更多