Home > Net >  How to get the sum of hour, minutes, and seconds in 2 columns?
How to get the sum of hour, minutes, and seconds in 2 columns?

Time:11-05

I'm using SQL Server as database. I have 2 columns in a table, newTime, oldTime.

Suppose I have value of 04:07:28 in the newTime column, and for oldTime, the value is 03:07:40.

The result should get the total of newTime and oldTime columns which is 07:15:08.

I tried the Split_String() function to easily split the numbers into hours, minutes, and seconds. But I have an issue in database the compatibility level is low and also I tried to set the compatibility_level to 130 but I don't have permission to alter the database.

Is there any other way to sum up the two columns? Thank you!

CodePudding user response:

As mentioned in comments - if you're storing time values, you should really be using the TIME datatype - not a VARCHAR ..... always use the most appropriate datatype - no exceptions.

Anyway - since you have VARCHAR, the statement get a bit convoluted - but here you go:

SELECT 
    DATEADD(SECOND, DATEDIFF(SECOND, 0, CAST(NewTime AS TIME)), CAST(OldTime AS TIME)) 
FROM 
    dbo.YourTableNameHere

which would look a lot easier with TIME columns, of course:

SELECT 
    DATEADD(SECOND, DATEDIFF(SECOND, 0, NewTime), OldTime) 
FROM 
    dbo.YourTableNameHere
  • Related