How do I add duration to string of format hhmm and convert it back to string?

casting, int, sql, sql-server, varchar

Solution

The assumption is that the question states the time will always be in 4 digit format hhmm. The query extracts hh and mm from the string and converts into time. The duration in minutes is added to this time value and then converted back to string format hh:mm using the CONVERT function and the colons are removed from the string to get back to the original format.

Click here to view the demo in SQL Fiddle.

Script:

CREATE TABLE timevalues
(
        timestring  VARCHAR(20) NOT NULL
    ,   duration    INT NOT NULL
);

INSERT INTO timevalues (timestring, duration) VALUES
    ('1145', 30),
    ('2345', 25),
    ('0815', 125);

SELECT      timestring
        ,   duration
        ,   REPLACE(CONVERT(VARCHAR(5), DATEVALUE, 108), ':', '') AS newtimevalue
FROM
(
    SELECT  timestring
        ,   duration
        ,   DATEADD(MINUTE, 
                    duration, 
                    CAST(
                            (   SUBSTRING(timestring, 1, 2) + ':' + 
                                SUBSTRING(timestring, 3, 2)
                            ) AS DATETIME
                        )
                    ) AS DATEVALUE 
    FROM    timevalues
) T1;

Output:

timestring duration newtimevalue
---------- -------- -------------
  1145        30      1215
  2345        25      0010
  0815       125      1020

Problem

I have two columns in a table that need to be added together. One of them is a varchar(4) with military time, minus the colon, including preceding 0s. Another one is an int which describes the duration of an appointment in minutes. Basically I need to add the two together and keep it as a varchar(4), all in the same format as the first column. I've used SQL before, but not in any sophisticated manner. What would be the right approach to this? Thanks! I don't have to worry about stuff carrying over into the next day. For example: ``` time: '1145' duration: 45 sum: '1230' time: '0915' duration: 30 sum: '0945' (not '945') ```

Original source