需要使用函数从字符串变量使用SQL计算秒数之和

Pra*_*nty 6 sql-server postgresql sql-server-2008

在表中有一个名为Adventurous的持续时间列,该列的值如下。在``H''的后缀是小时,在``M''的后缀是分钟,在``S''的后缀是秒。选择小时,分钟和秒,然后将其全部转换为秒,即以秒为形式的所有小时,分和秒的总和。

Duration 
--------
PT10M13S
PT13M22S
PT1H2M18S
PT11S
Run Code Online (Sandbox Code Playgroud)

我尝试使用如下所示的子字符串和charindex并尝试创建一个函数,但出现错误:

Declare @Duration varchar(30) ='PT16H13M42S', @Dur varchar(10)
Declare @hours int
declare @mins int
declare @secs int
declare @len int

select @len = len(substring (@Duration, 3, len(@Duration))), @Dur=substring (@Duration, 3, len(@Duration))
select @hours = charindex('H', @Dur)

select substring(@Dur, 1, @hours-1)

select @Duration=substring (@Dur, @hours+1, len(@Dur))
select @mins = charindex('M', @Duration)

select substring(@Duration, 1, @mins-1)

select @Dur=substring (@Duration, @mins+1, len(@Duration))
select @secs= charindex('S', @Dur)

select substring(@Dur, 1, @Secs-1)

select @len, @Dur, @Duration
Run Code Online (Sandbox Code Playgroud)

示例PT1H2M18S = 1 * 3600 + 2 * 60 + 18 = 3738

小智 0

这就是我在字符串中移动并提取正确的整数值的方法。要偏移的字符数可能会发生变化,具体取决于每小时、每分钟和每秒是否可以有不同数量的字符。但原则应该能让你继续前进。

Declare @Duration varchar(30) ='PT16H13M42S'


select * from 
(values(substring(@Duration,CHARINDEX('PT',@duration)+2,(CHARINDEX('H',@Duration)-CHARINDEX('PT',@Duration))-2),
        substring(@Duration,CHARINDEX('H',@duration)+1,(CHARINDEX('M',@Duration)-CHARINDEX('H',@Duration))-1),
        substring(@Duration,CHARINDEX('M',@duration)+1,(CHARINDEX('S',@Duration)-CHARINDEX('M',@Duration))-1))) duration ([Hours], [Minutes], [Seconds]);
Run Code Online (Sandbox Code Playgroud)