简体   繁体   中英

Removing total days from Hhh:mm:ss

I have a varchar field that stores a duration for connections that occasionally goes into the days. I'm trying to separate the total number of days from the hh:mm:ss in this field so I can store them separately but I'm getting an out of range error whenever I try to convert this data to any type of datetime variation in order to datepart the days from the value and then deduct. Is their any way of doing this or will I need to resort to a crude charindex(':' just to remove the days?

You'll have to chop it up since it's not in a valid date or time format:

DECLARE @timeString VARCHAR(50) = '114:48:50'
SELECT   Day_CT = LEFT(@timeString ,CHARINDEX(':',@timeString )-1)/24
        ,Tm = CAST(CAST(LEFT(@timeString ,CHARINDEX(':',@timeString )-1)%24 AS VARCHAR(12))+STUFF(@timeString ,1,CHARINDEX(':',@timeString )-1,'') AS TIME)

This is one of the many reasons why dates and times shouldn't be stored in string data types, it makes using them ugly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM