创建具有条件的SQL作业

时间:2016-01-12 17:45:19

标签: sql email sql-server-2012 job-scheduling sql-agent-job

如果我在SQL 2012中有两个SQL脚本,并且我希望在其中一个脚本返回信息而另一个脚本没有返回信息时收到一封电子邮件,我该如何设置它?

select * 
from 
    doc_queue_pend 
where 
    create_timestamp < DATEADD(Minute, -20, GETDATE());
--want to see nothing

select *
from 
    doc_queue_final 
where 
    create_timestamp > DATEADD(Minute, -20, GETDATE());
--want to see something

1 个答案:

答案 0 :(得分:0)

计算每个查询的结果,然后使用if语句来决定是否发送电子邮件。

declare @doc_queue_pend  int 
declare @doc_queue_final int

select @doc_queue_pend = count(*) 
from doc_queue_pend 
where create_timestamp < DATEADD(Minute, -20, GETDATE());

select @doc_queue_final = count(*)
from doc_queue_final 
where create_timestamp > DATEADD(Minute, -20, GETDATE());

if @doc_queue_pend = 0 and @doc_queue_final > 0
begin
    exec sp_send_dbmail ...
end