如何在T-SQL中将时间(7)数据类型相加?

时间:2017-09-14 07:03:46

标签: tsql datetime timespan

如何在t-sql中将两次数据类型相加?

 declare @fTime time(7)='05:22';
 declare @tTime time(7)='06:00';
 declare @result time(7);

我用过这个但是没用。

set  @result=sum(@fTime+@tTime);

2 个答案:

答案 0 :(得分:1)

你可以像这样添加一分钟到另一个:

select dateadd(minute,datediff(minute,'00:00',@tTime),@fTime)

但是,请注意dlatikay的评论是正确的,time(7)不适用于持续时间。最好将持续时间存储为整数,例如存储分钟或秒数。

答案 1 :(得分:0)

你能用这样的东西吗?

DECLARE @fTime TIME(7) = '05:22';
DECLARE @tTime TIME(7) = '06:00';
DECLARE @result TIME(7);

SELECT @result = CAST([Hours] AS NVARCHAR) + ':' + CAST([Minutes] AS 
NVARCHAR)
FROM (
SELECT cast(TotalTime AS INT) / 60 AS [Hours]
    ,CAST(TotalTime AS INT) % 60 AS [Minutes]
FROM (
    SELECT fTime + tTime AS TotalTime
    FROM (
        SELECT cast(SUBSTRING(cast(@ftime AS NVARCHAR), 1, 2) AS INT) * 60 + 
CAST(substring(cast(@ftime AS NVARCHAR), 4, 2) AS INT) AS fTime
            ,cast(SUBSTRING(cast(@tTime AS NVARCHAR), 1, 2) AS INT) * 60 + 
CAST(substring(cast(@tTime AS NVARCHAR), 4, 2) AS INT) AS tTime
        ) x
    ) y
) z

SELECT @result