我在SQL Server R2中安排了很多作业。 每项工作可能包含几个步骤。
我想要每个工作中的每一步和每一步的拉伸状态,拉伸状态,拉伸结构,拉伸,消息,以及每个步骤。
我向我提出这个查询工作正常。
唯一的问题是,它不允许我将 LastRunDateTime 字符串转换为 DateTime
SELECT
[sJOB].[job_id] AS [JobID],
[sJOB].[name] AS [JobName],
[sJOBS].step_name AS [StepName],
CASE
WHEN [sJOBS].[last_run_date] IS NULL OR [sJOBS].[last_run_time] IS NULL THEN NULL
ELSE
CAST(CAST([sJOBS].[last_run_date] AS VARCHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJOBS].[last_run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':') AS DATETIME)
END AS [LastRunDateTime],
CASE [sJOBH].[run_status]
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
WHEN 4 THEN 'Running' -- In Progress
END AS [LastRunStatus],
STUFF(
STUFF(RIGHT('000000' + CAST([sJOBS].[last_run_duration] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS [LastRunDuration (HH:MM:SS)],
[sJOBH].[message] AS [LastRunStatusMessage],
CASE [sJOBSCH].[NextRunDate]
WHEN 0 THEN NULL
ELSE CAST(
CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END AS [NextRunDateTime]
FROM
(SELECT * FROM [msdb].[dbo].[sysjobs] WHERE enabled = 1) AS [sJOB]
LEFT JOIN sysjobsteps [sJOBS]
ON([sJOB].[job_id] = [sJOBS].[job_id])
LEFT JOIN (
SELECT
[job_id],
MIN([next_run_date]) AS [NextRunDate],
MIN([next_run_time]) AS [NextRunTime]
FROM [msdb].[dbo].[sysjobschedules]
GROUP BY [job_id]
) AS [sJOBSCH]
ON [sJOB].[job_id] = [sJOBSCH].[job_id]
LEFT JOIN (
SELECT
[job_id],
[run_date],
[run_time],
[run_status],
[run_duration],
[message],
ROW_NUMBER() OVER (
PARTITION BY [job_id]
ORDER BY [run_date] DESC, [run_time] DESC
) AS RowNumber
FROM [msdb].[dbo].[sysjobhistory]
WHERE [step_id] = 0
) AS [sJOBH]
ON [sJOB].[job_id] = [sJOBH].[job_id]
AND [sJOBH].[RowNumber] = 1
ORDER BY [JobName]
LastRunDateTime上的CAST()函数给出了以下错误
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
谁能告诉我什么错了?
答案 0 :(得分:1)
不能保证你有完全相同的问题,但在我测试过的系统上,我得到了同样的错误,因为某些工作步骤0
为{ last_run_date
的值。
我通过对您的查询的以下修正来修复此问题。也许这对你也有用。
...
CASE
WHEN [sJOBS].[last_run_date] IS NULL OR [sJOBS].[last_run_time] IS NULL THEN NULL
WHEN [sJOBS].[last_run_date] = 0 THEN NULL --<< line added here <<
ELSE
CAST(CAST([sJOBS].[last_run_date] AS VARCHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJOBS].[last_run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':') AS DATETIME)
END AS [LastRunDateTime],
...