SQL - Operand data type datetime2 is invalid for subtract operator

微笑、不失礼 提交于 2021-02-16 20:00:07

问题


I want to subtract the value of the first row from the value of the second row of column _timestamp (shown below). _number is the ordering column in my data.

and put the result in a new column called diff. I have tried it with the following query

use dbtest

select 
    t2._number, t2._timestamp, 
    coalesce(t2._timestamp - (select t1._timestamp from dbo.tcp t1 
                              where t1._number = t2._number + 1), t2._timestamp) as diff
from 
    dbo.tbl t2

but I am getting the following error.

Msg 8117, Level 16, State 1, Line 4
Operand data type datetime2 is invalid for subtract operator.

Any tips would be appreciated. I have a huge record and I want to automatically apply it for the entire column.I am using SQL Sever 2008.


回答1:


As mentioned in the comments, you can't subtract timestamps with - operator. Use DATEDIFF function instead. To get the difference of the current row and the next row's timestamps, use OUTER APPLY.

select t2._number,t2._timestamp, 
datediff(microsecond,t2._timestamp,t1._timestamp) as diff
from dbo.tbl t2
outer apply (select t1._timestamp 
             from dbo.tcp t1
             where t1._number = t2._number + 1) t1

Edit: To update a column named diff per the OP's comment,

with cte as (          
select t2._number,t2._timestamp, t2.diff,
datediff(microsecond,t2._timestamp,t1._timestamp) as diff_col
from t t2
outer apply (select t1._timestamp 
             from t t1
             where t1._number = t2._number + 1) t1
   )
update cte set diff=diff_col;



回答2:


It's indeed not feasible with the datetime2

DECLARE @t1 DATETIME2(7) = '2020-01-01 13:20:00.000'
DECLARE @t2 DATETIME2(7) = '2020-01-01 13:22:23.000'
 
SELECT  CONVERT(VARCHAR(50),@t2 - @t1, 108)

>> Operand data type datetime2 is invalid for subtract operator.

But when converted to a datetime, it gives a nice result ;-)

DECLARE @t1 DATETIME2(7) = '2020-01-01 13:20:00.000' 
DECLARE @t2 DATETIME2(7) = '2020-01-01 13:22:23.000'

SELECT  CONVERT(VARCHAR(50), CONVERT(DATETIME, @t2) - CONVERT(DATETIME, @t1), 108)

>> 00:02:23


来源:https://stackoverflow.com/questions/42908098/sql-operand-data-type-datetime2-is-invalid-for-subtract-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!