Sql-server – Combine datetime + string to make a proper datetime

datetimesql server

I need to take a DATETIME column (Column A) that contains only a date, then add a VARCHAR(5) column (Column B) which contains a 24-hour representation of a time (i.e. 1330) and combine them to get a valid DATETIME to be used in a DATEDIFF command.

So for example, Column A contains 2013-07-01 00:00:00.000 and Column B contains 1330. The result should be 2013-07-01 13:30:00.000.

Edit: just to claify things, this is an existing DB that stores the data this way, it is out of scope of my project to completely change how things work to make it store the data in a proper way. If I could I would but I can't so I am stuck with the multiple columns. Also the data in Column B will always be a 4 digit time as the input page has checks to make sure time is a valid military time format.

Best Answer

This will also deal with values < 10 AM that don't have all 4 digits. (Also that column should probably be CHAR(4) instead of VARCHAR(5) - or better yet, stop separating these and store a proper datetime value in the first place).

DECLARE @t TABLE(ColumnA DATETIME, ColumnB VARCHAR(5));

INSERT @t VALUES('20130701', '1330'),('20130701', '930');

SELECT CONVERT(DATETIME, CONVERT(CHAR(8), ColumnA, 112) 
    + ' ' + LEFT(RIGHT('0' + ColumnB, 4),2) 
    + ':' + RIGHT(ColumnB, 2))
FROM @t;