我是一个相对较新的DBA(不到一年),我的T-SQL技能仍需要一些(好的......很多)工作。
我正在使用注册服务器来监控我的MS SQL 2005,2008和2012环境。我每天使用以下脚本来监视我的代理作业。这个脚本非常适合我需要的东西。但是,它的工作信息/状态可以追溯到几年前。我想仅返回最近x天的状态;但是我修改这个脚本的尝试都没有成功。
这是脚本:
SELECT
[sJOB].[job_id] AS [JobID]
, [sJOB].[name] AS [JobName]
, [sJSTP].[step_uid] AS [StepID]
, [sJSTP].[step_id] AS [StepNo]
, [sJSTP].[step_name] AS [StepName]
, CASE [sJSTP].[last_run_outcome]
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
WHEN 5 THEN 'Unknown'
END AS [LastRunStatus]
, STUFF(
STUFF(RIGHT('000000' + CAST([sJSTP].[last_run_duration] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS [LastRunDuration (HH:MM:SS)]
, [sJSTP].[last_run_retries] AS [LastRunRetryAttempts]
, CASE [sJSTP].[last_run_date]
WHEN 0 THEN NULL
ELSE
CAST(
CAST([sJSTP].[last_run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJSTP].[last_run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END AS [LastRunDateTime]
FROM
[msdb].[dbo].[sysjobsteps] AS [sJSTP]
INNER JOIN [msdb].[dbo].[sysjobs] AS [sJOB]
ON [sJSTP].[job_id] = [sJOB].[job_id]
WHERE [sJSTP].[last_run_outcome] <>1
--AND DATEDIFF(day,[sJSTP].[last_run_date],getdate()) < 31
--AND [sJSTP].[last_run_date] >= DATEADD(DAY, -7, DATEDIFF(DAY, 0, GETDATE()))
ORDER BY [JobName], [StepNo]
&#13;
我包含了我最近尝试修改脚本的两个尝试。可以预见的是,他们都犯了以下错误:
: Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type datetime
&#13;
我的猜测是数据类型存在问题(数字与日期时间)。我很乐意修改这个脚本。
由于
答案 0 :(得分:0)
Field&#34; last_run_date&#34;存储为8位INT,SQL Server不会隐式转换为日期。它将隐式地将CHAR(8)强制转换为日期。所以就这样做
CAST(last_run_date AS CHAR(8)) > ...
比较这些例子:
- 这个失败
select case when 20150527 >= DATEADD(DAY, -7, DATEDIFF(DAY, 0, GETDATE())) then 1 else 0 end
- 这个成功了
select case when cast(20150527 as CHAR(8)) >= DATEADD(DAY, -7, DATEDIFF(DAY, 0, GETDATE())) then 1 else 0 end
所以只需更正WHERE子句以包含CAST:
WHERE [sJSTP].[last_run_outcome] <>1
AND cast([sJSTP].[last_run_date] as CHAR(8)) >= DATEADD(DAY, -7, DATEDIFF(DAY, 0, GETDATE()))