SQL SERVER - Convert String in Days

Asked

Viewed 172 times

5

How can I convert this string in days?

Example: return "2 days and 2 hrs"?

SELECT '50:00:00'

2 answers

5


Using Ricardo’s answer and solving the case of more than 99 hours in the input string would look like this:

declare @h int, @m int, @s int, @time varchar(8), @pos int
set @time = '155:00:00'
set @pos = CHARINDEX( ':', @time )
set @h = SUBSTRING(@time, 1, @pos-1)
set @m = SUBSTRING(@time, @pos+1, 2)
set @s = SUBSTRING(@time, @pos+4, 2)

select cast (@h/24 as nvarchar(10)) + 'dias, ' + cast (@h%24 as nvarchar(10)) + 'horas, ' + cast (@m as nvarchar(2)) + 'minutos, ' + cast (@s as nvarchar(2)) + 'segundos'
  • 2

    another solution, if using the SQL Server 2016 is to use Function STRING_SPLIT in place of CHARINDEX to separate the values: STRING_SPLIT

3

Divide '50' by 24 and you will get the number of days.
Take the rest of the division '50' by 24 and you’ll get the rest of the hours.
Minutes and seconds don’t need to calculate.

declare @h int, @m int, @s int, @time varchar(8)
set @time = '50:00:00'
set @h = SUBSTRING(@time, 1, 2)
set @m = SUBSTRING(@time, 4, 2)
set @s = SUBSTRING(@time, 7, 2)

select cast (@h/24 as nvarchar(10)) + 'dias, ' + cast (@h%24 as nvarchar(10)) + 'horas, ' + cast (@m as nvarchar(2)) + 'minutos, ' + cast (@s as nvarchar(2)) + 'segundos'

See an example here: http://sqlfiddle.com

  • 1

    But it has restrictions with values greater than 99 hours.

  • 1

    Yes, well observed, I think do the split of the string using ":" as a separator help avoid this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.