How to convert 3/4 Character Integer to 24 Hour Ti

2019-08-08 12:44发布

I have a doc Column of Date Time format, but it always leaves the time blank, and I have a time field which is an integer which represents hours and minutes (not including seconds). I would like to convert the time and add it to the date so that I can select Max(datetime) and return a single value.

Here is my SQL Fiddle.

The Data is stored as follows:

DocDate                 DocTime
2013-04-29 00:00:00.000 1416
2013-04-29 00:00:00.000 1027
2013-04-29 00:00:00.000 823

I'd like to convert it to:

DateTime
2013-04-29 14:16:00.000 
2013-04-29 10:27:00.000 
2013-04-29 08:23:00.000 

4条回答
对你真心纯属浪费
2楼-- · 2019-08-08 13:07

Some simple date arithmetics will do it;

SELECT DATEADD(mi, FLOOR(DocTime/100)*60 + DocTime%100, DocDate) FROM OPOR;

An SQLfiddle to test with.

查看更多
迷人小祖宗
3楼-- · 2019-08-08 13:07

Just treat them both as datetimes and add together:

select  DocDate,
        DocTime,
        DocDate + stuff(right('0000'+cast(DocTime as varchar(4)), 4), 3, 0, ':')
from    OPOR

See example: http://sqlfiddle.com/#!3/8e22e/54

查看更多
混吃等死
4楼-- · 2019-08-08 13:23

see Sql fiddle

select 
dateadd(hh, convert(int,left(doctime,len(doctime)-2)),
dateadd(mi, convert(int,right(doctime,2)) ,docdate))
from opor

Using dateadd to add the hours ( left one or two chars of doctime) and the minutes (right 2 chars of doctime) to the date.

查看更多
Ridiculous、
5楼-- · 2019-08-08 13:27

This should do:

;WITH CTE AS
(
    SELECT  *,
            DATEADD(HOUR,DOCTIME/100,DOCDATE) DocDateHour,
            CAST(RIGHT(DOCTIME,2) AS INT) DocTimeOnly
    FROM OPOR
)
SELECT DATEADD(MINUTE,DocTimeOnly,DocDateHour)
FROM CTE

And here is the modified sqlfiddle for you to try.

查看更多
登录 后发表回答