操作数数据类型时间对减法运算符无效

时间:2018-05-04 15:24:33

标签: sql-server

我遇到的问题是这段代码对我不起作用。就这一切而言,就我所知,一切都是正确的,但我不断收到错误。我知道这是其他问题的重复,我已经搜索过它们,但没有任何对我有用

convert(time(0),(isnull(solver_endtime,'')-isnull(solver_starttime,''))) as solverruntime,

如果我错过了某些内容,这是完整的代码

IF OBJECT_ID('staging.dbo.Log_Batch_Report_2', 'U') IS NOT NULL
merge into staging.dbo.log_batch_report_2 a
using 
(select batch,
    starttime,
    endtime,
    convert(time(0),(isnull(endtime,'')-isnull(starttime,''))) as totalruntime,
    convert(time(0),(isnull(solver_endtime,'')-isnull(solver_starttime,''))) as solverruntime,
    convert(time(0),((isnull(endtime,'')-isnull(starttime,''))- (isnull(solver_endtime,'')-isnull(solver_starttime,'')))) as non_solverruntime,
    to_time
from staging.dbo.log_batch_report
) b
on a.batch=b.batch and a.starttime=b.starttime and a.endtime=b.endtime
when matched then update set a.batch=a.batch
when not matched then insert (batch,batchdate,logility_up_time,starttime,endtime,totalruntime,solverruntime)
values (b.batch,b.starttime,b.endtime,b.starttime,b.endtime,b.totalruntime,b.solverruntime);

修改

这是我从此代码中的totalruntime行获得的内容。那和其他两行有什么区别?

enter image description here

2 个答案:

答案 0 :(得分:0)

要获得以下两个日期之间的区别,您可以使用以下内容:

SELECT starttime, endtime, 
    Days = DATEDIFF(second, starttime, endtime) / 86400,
    Hours = DATEDIFF(second, starttime, endtime) % 86400 / 3600,
    Minutes = DATEDIFF(second, starttime, endtime) % 3600 / 60,
    Seconds = DATEDIFF(second, starttime, endtime) % 60

答案 1 :(得分:0)

我确信DATEDIFF有效,但我学到的是我的更大问题是数据错误,其中STARTDATE晚于ENDDATE,提供否定答案。因此我需要在那里添加一个子句,以便在ENDDATE>时进行数学运算。 STARTDATE

IF OBJECT_ID('staging.dbo.Log_Batch_Report_2', 'U') IS NOT NULL
merge into staging.dbo.log_batch_report_2 a
using 
(select batch,
    starttime,
    endtime,
    solver_starttime,
    solver_endtime,
    CASE WHEN endtime>starttime THEN convert(time(0),(isnull(endtime,''))-(isnull(starttime,''))) 
        ELSE null
    END as totalruntime,
    CASE WHEN solver_endtime>solver_starttime THEN convert(time(0),(isnull(solver_endtime,''))-(isnull(solver_starttime,''))) 
        ELSE null
    END as solverruntime,
    CASE WHEN endtime>starttime and solver_endtime>solver_starttime and (endtime-starttime)>(solver_endtime-solver_starttime) 
            THEN convert(time(0),((isnull(endtime,'')-isnull(starttime,''))-((isnull(solver_endtime,'')-isnull(solver_starttime,''))))) 
        ELSE null
    END as non_solverruntime,
    to_time
from staging.dbo.log_batch_report
) b
on a.batch=b.batch and a.starttime=b.starttime and a.endtime=b.endtime
when matched then update set a.batch=a.batch
when not matched then insert (batch,batchdate,logility_up_time,solver_starttime,solver_endtime,starttime,endtime,totalruntime,solverruntime)
values (b.batch,b.starttime,b.endtime,b.solver_starttime,b.solver_endtime,b.starttime,b.endtime,b.totalruntime,b.solverruntime);

这在技术上可能不正确,但到目前为止,它正在产生我所寻找的小时:分钟:秒格式的差异,即使时间是在不同的日子