【问题标题】:The latest two status of sql server agent jobssql server 代理作业的最新两种状态
【发布时间】:2015-07-16 08:17:45
【问题描述】:

我需要进行查询以获取 sql server 代理作业的状态。

棘手的部分是,我都想要作业上次失败的时间(如果有的话)和上次成功运行的时间 - 这可能吗?

到目前为止,我只能获得最后一次成功运行或最后一次失败的作业运行。

SELECT 
job.name
,jobh.run_date 
,DATEADD(HOUR, (jobh.run_time / 1000000) % 100, 
DATEADD(MINUTE, (jobh.run_time / 10000) % 100,
DATEADD(SECOND, (jobh.run_time / 100) % 100,
DATEADD(MILLISECOND, (jobh.run_time % 100) * 10, 
cast('00:00:00' as TIME(0)))))) AS 'tidspunkt'
,jobh.run_duration
FROM msdb.dbo.sysjobhistory jobh
JOIN [msdb].[dbo].[sysjobs] job ON jobh.job_id = job.job_id
WHERE jobh.step_id = 0
AND jobh.message LIKE '%failed%'
AND (jobh.run_date = CONVERT(VARCHAR, GETDATE(), 112) OR jobh.run_date =    CONVERT(VARCHAR, DATEADD(DAY, -1, GETDATE()), 112) )
AND job.name = 'UpdateCPR'
ORDER BY jobh.run_date DESC, jobh.run_time DESC

【问题讨论】:

    标签: sql-server sql-agent-job


    【解决方案1】:

    换行就好了……

    AND jobh.message LIKE '%failed%'
    

    ...跟随...

    AND (jobh.message LIKE '%failed%' OR jobh.message LIKE '%succeeded%')
    

    您将获得多行。如果您愿意,可以按 LIKE 结果对其进行分组,然后从两者中选择 TOP 1 以在一行中检索它。

    编辑

    使用它在一行中获取失败和成功信息。

    ;WITH jobRuns AS (
        SELECT
            job.job_id,
            job.name,
            jobh.run_time,
            jobh.run_duration,
            execStatus
        FROM msdb.dbo.sysjobhistory jobh
        JOIN msdb.dbo.sysjobs job 
            ON jobh.job_id = job.job_id
        CROSS APPLY(
            SELECT execStatus = CASE 
                WHEN jobh.message LIKE '%failed%' THEN 0 
                WHEN jobh.message LIKE '%succeeded%' THEN 1 END) ext
        WHERE 
            jobh.step_id = 0
            and job.name LIKE '%testjob%'
        /*GROUP BY
            job.job_id,
            job.name,
            jobh.run_time,
            execStatus*/)
    ,lastRuns AS (
        SELECT TOP 1
            jobRuns.job_id,
            jobRuns.name,
            run_time_failed = failed.run_time,
            run_duration_failed = failed.run_duration,
            run_time_succeeded = success.run_time,
            run_duration_succeeded = success.run_duration
        FROM jobRuns
        CROSS APPLY(
            SELECT TOP 1 run_time, run_duration
            FROM jobRuns
            WHERE execStatus = 0
            ORDER BY run_time DESC) failed
        CROSS APPLY(
            SELECT TOP 1 run_time, run_duration
            FROM jobRuns
            WHERE execStatus = 1
            ORDER BY run_time DESC) success
    )
    SELECT * 
    FROM lastRuns
    

    【讨论】:

    • 在上面的查询中,您将如何逐个进行该组的操作,以查询一行中的失败和成功状态?
    • 你就是男人!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多