Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert varchar to time

Tags:

sql

sql-server

I have tried the links available here for similar questions before but it does not work. So I am posting my case here.

I have time in format:

09:47:11:895799

This is stored as varchar(50) in my Microsoft SQL Server database.

I am trying to convert it to time format as on this link.

hh:mm:ss[.nnnnnnn]

Can you please help?

like image 388
Zanam Avatar asked Jan 12 '13 13:01

Zanam


People also ask

Can I convert varchar to date?

How do I change the datatype of a column from varchar to date in SQL? Add a column to your table to hold the DATE data. ALTER TABLE my_table ADD (new_col DATE); Set this new column's value to hold the old_column's value converted to a DATE value.

Can I store time in varchar?

You can store date in a VARCHAR column, you can also store non-dates in that VARCHAR column.

How do I convert text to date in SQL?

Use the function TO_DATE() to convert a text value containing a date to the date data type. This function takes two arguments: A date value. This can be a string (a text value) or a text column containing date information.

How do you resolve the conversion of a varchar data type to a datetime data type resulted in an out of range value?

Answer: The error is due to an invalid date format being saved to the custom_rmh_rooms_history SQL table. To resolve this issue, the Windows Regional settings need to be modified and the Short Date format needs to be in MM/dd/yyyy format.


2 Answers

The string is in the wrong format. It should be 09:47:11.895799. You need to replace the final : with a .

SELECT CAST(STUFF('09:47:11:895799', 9,1,'.') AS TIME)
like image 178
Martin Smith Avatar answered Oct 24 '22 00:10

Martin Smith


You can also make your string as hh:mi:ss:mmm (24 hour format) and then convert as time. That means trimming out last 3 digits from your milli seconds without replacing last ':' with '.'

Here is MSDN link for more details of formatting. Here is working example of SQL Fiddle

DECLARE @s varchar(50) = '09:47:11:895799'
SELECT Convert(time, Left(@s,Len(@s)-3), 114)
like image 21
Kaf Avatar answered Oct 23 '22 23:10

Kaf