如何在SQL Server中将hh:mm:ss转换为秒超过24小时

时间:2015-07-15 08:26:27

标签: sql sql-server sql-server-2008

我有一个表名tblAttend,其中一个名为WorkHrs的列的数据类型为varchar

简单选择查询的结果是

enter image description here

我总结这个列的值,并在几秒钟内得到结果,我的查询是

select sum(DATEDIFF(SECOND, '0:00:00', WorkHrs )) 
from tblAttend

并显示此输出:

enter image description here

现在的问题是,当WorkHrs的总和大于24小时时,它会引发错误:

enter image description here

你有什么建议可以解决这个问题?提前致谢

6 个答案:

答案 0 :(得分:1)

我已经实现了以下功能,以便在我的项目管理中使用它:

/****** Object:  UserDefinedFunction [dbo].[Seconds]    Script Date:     10/6/2017 12:00:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
select [dbo].[Seconds]('24:00:00'),(24*3600)
select [dbo].[Seconds]('102:56:08'),(102*3600+56*60+8)
*/
ALTER FUNCTION [dbo].[Seconds] (@Time as varchar(50))
RETURNS int
BEGIN
declare @S int, @H int
set @H=cast(SUBSTRING(@Time,1,CHARINDEX(':',@Time)-1) as int)
IF @H<24
set @S=DATEDIFF(SECOND, '0:00:00', @Time)
ELSE BEGIN
    set @H=@H-23
    set @Time = '23'+SUBSTRING(@Time,CHARINDEX(':',@Time),LEN(@Time)-2)
    set @S = (@H*3600)+DATEDIFF(SECOND, '0:00:00', @Time)
END
RETURN @S
END

答案 1 :(得分:0)

试试这个:

SELECT DATEDIFF(SECOND, CONVERT(DATE,GETDATE()), GETDATE())

答案 2 :(得分:0)

我认为您可以将时间的各个部分(小时,分钟和秒)隔离开,而不是总结所需的内容,请看一下:

declare @tbl table(WorkHrs VARCHAR(8))
insert into @tbl(WorkHrs) values ('02:29:11')
insert into @tbl(WorkHrs) values ('25:00:11')
-- Sum in minutes
SELECT TRY_CAST(([HOURS] * 60) + [MINUTES] + ([SECOND] / 60) AS INT) as TotalInMinutes
FROM (
SELECT 
    -- Use this aproach to get separated values 
    SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
    SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
    SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND] -- probably you can ignore this one
    FROM @tbl
)
tbl
-- Or try to sum in seconds
SELECT TRY_CAST(([HOURS] * 3600) + ([MINUTES] * 60) + [SECOND] AS INT) as TotalInSeconds
FROM (
SELECT 
    -- Use this aproach to get separated values 
    SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
    SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
    SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND]
    FROM @tbl
)
tbl

它将像这样返回给您:

enter image description here

我希望它可以帮助

答案 3 :(得分:0)

您可以尝试这样:

SELECT Sec=SUM((DATEPART(HOUR,column name)*3600)+(DATEPART(MINUTE,column name)*60)+(DATEPART(Second,column name)))
FROM [TableName]

答案 4 :(得分:0)

尝试:

DECLARE @DURATION TIME = '01:43:24'

SELECT DATEDIFF(SECOND, '1/1/1900', CONVERT(DATETIME, @DURATION))

答案 5 :(得分:-1)

您可以简单地使用TIME_TO_SEC函数:

SELECT TIME_TO_SEC(WorkHrs) FROM tblAttend;