SQL Server Convert integer data type to time

at0kjp5o  于 2023-03-28  发布在  其他
关注(0)|答案(2)|浏览(157)

My table lists the date and time fields as integer data types. I need to convert them to normal date formats. I have the date field done. How can I convert the time field with SQL?
| AppointmentDate | AppointmentTime | NewDate | NewTime |
| ------------ | ------------ | ------------ | ------------ |
| 20230329 | 830 | 3/29/2023 | 8:30 AM |
| 20230516 | 1330 | 5/16/2023 | 1:30 PM |
| 20230403 | 1500 | 4/3/2023 | 3:00 PM |
| 20230329 | 1020 | 3/29/2023 | 10:20 AM |

laik7k3q

laik7k3q1#

Do this:

TimeFromParts(AppointmentTime/100, AppointmentTime%100, 0, 0, 0)

TimeFromParts() Documentation

Lots of people will use a string-based solution instead, because that's the obvious answer. However, this is a case where the obvious answer is definitely not your best choice. Thanks to cultural/internationalization issues, string-based solutions will pretty much always be slower and more error-prone. If this is how you handled the date conversion, you might also want to revise the Date code to use the equivalent DateFromParts() method:

DateFromParts(AppointmentDate / 10000, AppointmentDate / 100 % 100, AppointmentDate % 100)

If it were me, I'd also combine Date and Time into the same column :

DateTimeFromParts(AppointmentDate / 10000, AppointmentDate / 100 % 100, AppointmentDate % 100, AppointmentTime / 100, AppointmentTime % 100, 0, 0)
5lwkijsr

5lwkijsr2#

I usually do a double cast for int => varchar => date:

SELECT CAST(CAST(20230329 AS VARCHAR(8)) AS DATETIME)

For time, it's something like:

SELECT CAST(STUFF(RIGHT('0' + CAST(830 AS VARCHAR(4)), 4), 3, 0, ':') AS TIME)

You pad out the time to simplify the insert of ':' and then cast to time.

To combine into datetime:

SELECT CAST(CAST(20230329 AS VARCHAR(8)) + ' ' + STUFF(RIGHT('0' + CAST(830 AS VARCHAR(4)), 4), 3, 0, ':') AS DATETIME)

相关问题