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 |
2条答案
按热度按时间laik7k3q1#
Do this:
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:If it were me, I'd also combine Date and Time into the same column :
5lwkijsr2#
I usually do a double cast for int => varchar => date:
For time, it's something like:
You pad out the time to simplify the insert of ':' and then cast to time.
To combine into datetime: