Since your tempo_indisponivel
field refers to durations of time that may contain values greater than 24h, you can not convert it to type Time
.
The field of type Time in SqlServer refers to the time of day based on a 24-hour clock. Allowed values should be in the range of 00:00:00.0000000
to 23:59:59.9999999
.
My suggestion would be to work with the unit of time in seconds (using int
). To convert to seconds, assuming the varchar
field stores the time in horas:minutos:segundos
format, just do:
declare @tempo varchar(9) = '72:05:38'
select cast( left( @tempo,charindex(':', @tempo) - 1) as int) * 3600
+cast( substring( @tempo,charindex(':', @tempo) + 1 ,2) as int) * 60
+cast( right( @tempo,2) as int) as tempo_em_segundos
--Resultado: 259538
To convert back the duration time in seconds to type varchar
, just do:
declare @tempo_em_segundos int = 259538
select cast(@tempo_em_segundos/3600 as varchar(3))
+':'+right('0'+cast(@tempo_em_segundos%3600/60 as varchar(2)) ,2)
+':'+right('0'+cast(@tempo_em_segundos%60 as varchar(2)) ,2)
--Resultado: '72:05:38'
Another solution
Another way to work with "time durations" in SqlServer would be to use the DateTime having the default value 01/01/1900 00:00:00
as the start date (D0).
The durations would be represented as a displacement from D0. For example:
Duração Representação em DateTime Significado
12:30:01 01/01/1900 12:30:01 0 Dia 12h 30min 01seg
25:15:30 02/01/1900 01:15:30 1 Dia 01h 15min 30seg
To convert a duration of time varchar
to DateTime
, the following query could be used:
declare @tempo varchar(9) = '72:05:38'
select dateadd
(day
,cast( left( @tempo,charindex(':', @tempo) - 1) as int) / 24
,cast( cast( cast( left( @tempo,charindex(':', @tempo) - 1 )
as int) % 24
as varchar(3)) + substring( @tempo,charindex(':', @tempo) ,6)
as datetime) )
--Resultado: 04/01/1900 00:05:38