我尝试用HH投射时间:MM格式它工作正常但是当我插入超过23小时的时间,即24:0
时,它会产生错误
"将varchar数据类型转换为日期时间数据类型会导致超出范围的值。 "
以下是代码
CREATE TABLE mytable
(
timeduration varchar(25)
)
INSERT INTO mytable VALUES ('05:30')
INSERT INTO mytable values ('24:0')
INSERT INTO mytable values ('04:33')
-- OUTPUT SHOULD BE 34:3 MINUTES
select CAST
(
(SUM (datepart(hh, convert (varchar, timeduration, 108))) +
(sum(datepart(mi, convert (varchar, timeduration, 108)))/60) ) AS VARCHAR(2)
)
+ ':' +
CAST
(
sum(datepart(mi, convert (varchar, timeduration, 108))) - 60 * (sum(datepart(mi, convert (varchar, timeduration, 108)))/60)
as VARCHAR(2))
from mytable
答案 0 :(得分:1)
你的问题是'24:00',如果你想让它工作,这里应该是'00:00'。 但是你必须为你的查询添加案例表达式。我建议你改写为:
DECLARE @mytable TABLE
(
timeduration VARCHAR(25)
)
INSERT INTO @mytable
VALUES ( '05:30' )
INSERT INTO @mytable
VALUES ( '24:0' )
INSERT INTO @mytable
VALUES ( '04:33' );
WITH cte
AS ( SELECT SUM(CAST(SUBSTRING(timeduration, 1, CHARINDEX(':', timeduration) - 1) AS INT)) AS Hours ,
SUM(CAST(SUBSTRING(timeduration, CHARINDEX(':', timeduration) + 1, 5) AS INT)) AS Minutes
FROM @mytable
)
SELECT CAST(Hours + Minutes / 60 AS NVARCHAR(20)) + ':' + CAST(Minutes % 60 AS NVARCHAR(20)) AS Duration
FROM cte
输出:
Duration
34:3