我有以下脚本(全部使用系统数据库)。
以下是我的脚本。它基本上是一个用于识别运行时间超过240分钟的SQL Server代理作业的脚本。
--Step 1: Decide if anything is actually running longer than 240 mins
IF EXISTS
(
SELECT p.spid,
j.name,
p.program_name,
ISNULL(DATEDIFF(mi, p.last_batch, GETDATE()), 0) AS MinutesRunning,
p.last_batch
FROM master.sys.sysprocesses AS p
INNER JOIN sysjobs AS j
ON dbo.udf_SysJobs_GetProcessid(j.job_id) = SUBSTRING(p.program_name, 32, 8)
WHERE (p.program_name LIKE 'SQLAgent - TSQL JobStep (Job %') AND (ISNULL(DATEDIFF(mi, p.last_batch, GETDATE()), 0) >= 240)
)
--Step 2: Set the variable format and define a query
DECLARE @longjob NVARCHAR(MAX);
SET @longjob =
'SELECT p.spid,
j.name,
p.program_name,
ISNULL(DATEDIFF(mi, p.last_batch, GETDATE()), 0) AS MinutesRunning,
p.last_batch
FROM master.sys.sysprocesses AS p
INNER JOIN sysjobs AS j
ON dbo.udf_SysJobs_GetProcessid(j.job_id) = SUBSTRING(p.program_name, 32, 8)
WHERE (p.program_name LIKE ''SQLAgent - TSQL JobStep (Job %'') AND (ISNULL(DATEDIFF(mi, p.last_batch, GETDATE()), 0) >= 240)'
--Step 3: Execute the email and set content
EXEC msdb.dbo.sp_send_dbmail
@profile_name = N'SERVER',
@recipients = 'EMAIL',
@subject = 'SUBJECT',
@body = 'TEXT',
@query = @longjob,
@attach_query_result_as_file = 1;
我的目标是仅在有长时间运行的作业时触发电子邮件 - 但每次运行时似乎都会发送一封电子邮件(结果为空白)。
答案 0 :(得分:0)
想出来......
就我而言, IF COUNT> 0 比 IF EXISTS 更好地工作。
{{1}}