Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert varchar to date

I (unfortunately) have some dates that were saved into varchar columns. These columns contain dates in the following format:

mmddyy

For example:

010110

I need to import these values into a table which is set to datetime and formats dates like this:

2010-09-17 00:00:00.000

How can I convert the string above into a datetime value below?

like image 882
Dave Mackey Avatar asked Oct 06 '10 21:10

Dave Mackey


People also ask

How do I convert text to date in SQL?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.

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.

Can we cast varchar to date in Teradata?

In Teradata, CAST function can be used to cast string/varchar to date. Format string can be used. For example, B represents blank/space while YYYY represents years.


1 Answers

The CAST function will do this, the problem is that it will assume you first 2 digits are year. This should for for you:

SELECT CAST((RIGHT('010110',2) + LEFT('010110',4)) AS DATETIME)

This is assuming that all dates are MMDDYY.

like image 100
Dustin Laine Avatar answered Nov 04 '22 05:11

Dustin Laine