将HHH:MM:SS转换为秒

时间:2018-02-01 13:00:47

标签: sql-server tsql datetime sql-server-2012

从源数据库中,我得到HH:MM:SS为832:24:12

目前我正在使用以下声明,这对大多数情况都很好hh:mm:ss但是当小时数超过99时它会失败

ISNULL(LEFT(COLUMN,2) * 3600  + RIGHT(LEFT(COLUMN,5),2) * 60 + RIGHT(COLUMN, 2) ,0)

4 个答案:

答案 0 :(得分:4)

只是对原始

进行小调整的另一个选项

示例

Declare @V varchar(50) = '832:24:12'

Select (left(@V,charindex(':',@V)-1)*3600) + (left(right(@V,5),2)*60) + right(@v,2)

<强>返回

2996652

答案 1 :(得分:2)

您可以使用PARSENAME()函数来使用棘手的解决方案。

DECALRE @Hours INT = 0, @Minutes INT = 0 , @Seconds INT = 0

SELECT @Hours =  PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),4),
       @Minutes = PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),3),
       @Seconds = PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),2)

SELECT @Hours * 3600  + @Minutes * 60 + @Seconds as TotalSeconds

我正在取代&#39;:&#39;用&#39;。&#39;附加虚拟字符序列后的字符&#39; 00&#39; PARSENAME()函数通过拆分为分隔数据来工作。

用于表格查询

SELECT   PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),4) * 3600 +
         PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),3) * 60 +
         PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),2) As TotalSecs
FROM TableName

答案 2 :(得分:1)

这是猜测,但是......

CREATE TABLE #Test (TimeString varchar(10))
INSERT INTO #Test
VALUES ('832:24:12')

SELECT TimeString,
       (LEFT(TimeString, H.CI - 1) * 3600) + (SUBSTRING(TimeString,H.CI +1, M.CI - H.CI -1) * 60) + (RIGHT(TimeString, LEN(TimeString) - M.CI))
FROM #Test T
     CROSS APPLY (VALUES(CHARINDEX(':',TimeString))) H(CI)
     CROSS APPLY (VALUES(CHARINDEX(':',TimeString, H.CI+1))) M(CI);

DROP TABLE #Test;

答案 3 :(得分:0)

Hours can be the leftwards chars minus 6 positions to take into account the positions for minutes and seconds in the string (:##:##). The minutes can accessed by taking the left 2, of the rightmost 5 chars. The seconds are the right 2 chars.

Ex:

DECLARE @tempval varchar(100) = '832:24:12'

SELECT LEFT(@tempval, LEN(@tempval) - 6) * 3600
      +LEFT(RIGHT(@tempval, 5), 2) * 60
      +RIGHT(@tempval, 2)

Returns

2996652