Hello,
In SQL Server 2005, I am working with a table that has a nvarchar column that stores times in the format "8:30 AM" as a string. I need to sort by the actual time, not just the characters, so for example "8:00 AM" needs to come before "12:00 PM." Unfortunately converting the field to a datetime or smalldatetime field is not an option.
I have tried the following:
and
I have tried substituting smalldatetime for datetime and that doesn't work either. The error message is "Conversion failed when converting datetime from character string."
I've thought about trying to Group By just the "AM" and "PM" parts of the field, but the combination of single digit and double-digit hours means it won't always be in the same place, and I can't count from the end because sometimes there are a few spaces included after the AM or PM.
Any ideas are greatly appreciated.
Thanks,
Josh
In SQL Server 2005, I am working with a table that has a nvarchar column that stores times in the format "8:30 AM" as a string. I need to sort by the actual time, not just the characters, so for example "8:00 AM" needs to come before "12:00 PM." Unfortunately converting the field to a datetime or smalldatetime field is not an option.
I have tried the following:
Code:
SELECT CONVERT(datetime, txtStartTime) As StartTime
FROM tblFinalSchedule
ORDER BY StartTime
Code:
SELECT CAST(txtStartTime AS datetime) As StartTime
FROM tblFinalSchedule
ORDER BY StartTime
I've thought about trying to Group By just the "AM" and "PM" parts of the field, but the combination of single digit and double-digit hours means it won't always be in the same place, and I can't count from the end because sometimes there are a few spaces included after the AM or PM.
Any ideas are greatly appreciated.
Thanks,
Josh