添加新的计算列; Start_DateTime加上持续时间(时间)为End_datetime

时间:2018-06-01 08:11:41

标签: sql sql-server datetime calculated-columns

SQL Server代理作业;在msdb中,您有dbo.sysjobhistory,它为您提供Run_date和Run_time类型INT,可以使用dbo.agent_datetime轻松转换为Start_Datetime。我得到:2018-05-17 01:13:09.240

Run_duration也是INT。我用

STUFF(STUFF(RIGHT('000000' + CAST(jh.run_duration AS VARCHAR(6)), 6), 5, 0, ':'), 3, 0, ':') AS'Time_HH:MM:SS'

我得到27:31:20

我想将新列计算为End_datetime。 (即Start_datetime + Run_duration)我的工作运行时间超过24小时,所以日期也可以进入第二天。

从哪里开始?转换后或以原始INT

开头
Run_date, Run_time, Run_duration

最简单的脚本最有帮助。

3 个答案:

答案 0 :(得分:2)

你可以施放"持续时间"如datetime,请将其加到start_date

select  dbo.agent_datetime(run_date, run_time) START_TIME,
        STUFF(STUFF(RIGHT('000000' + CAST ( run_duration AS VARCHAR(6 ) ) ,6),5,0,':'),3,0,':') DURATION,
        CONVERT(datetime, dbo.agent_datetime(run_date, run_time)) +
        CONVERT(datetime, STUFF(STUFF(RIGHT('000000' + CAST ( run_duration AS VARCHAR(6 ) ) ,6),5,0,':'),3,0,':') ) AS END_TIME

from sysjobhistory

输出:

START_TIME              DURATION END_TIME
----------------------- -------- -----------------------
2017-06-11 04:00:01.000 01:05:33 2017-06-11 05:05:34.000
2017-06-18 04:00:00.000 01:05:30 2017-06-18 05:05:30.000
2017-06-18 04:00:00.000 01:05:30 2017-06-18 05:05:30.000

2018-01-28 04:00:00.000 02:15:07 2018-01-28 06:15:07.000
2018-01-28 04:00:00.000 02:15:07 2018-01-28 06:15:07.000
2018-02-04 04:00:00.000 02:14:29 2018-02-04 06:14:29.000
2018-02-04 04:00:00.000 02:14:30 2018-02-04 06:14:30.000
2018-02-11 04:00:01.000 02:18:47 2018-02-11 06:18:48.000
2018-02-11 04:00:00.000 02:18:48 2018-02-11 06:18:48.000
2018-02-18 04:00:01.000 02:18:18 2018-02-18 06:18:19.000

答案 1 :(得分:2)

将持续时间转换为秒并执行Dateadd

 SELECT convert(DATETIME, convert(VARCHAR(10), run_date))
        ,run_duration % 100 seconds
        ,DATEADD(ss, (run_duration % 100), convert(DATETIME, convert(VARCHAR(10), run_date))) 
              End_date
    FROM dbo.sysjobhistory

答案 2 :(得分:0)

这似乎对我来说更容易

    , DATEADD(SECOND, run_duration / 10000 * 3600 + run_duration % 10000 / 100 * 60 + run_duration % 100, 
msdb.dbo.agent_datetime(jh.run_date, jh.run_time)) AS End_DateTime