2

I have below sample data:

03202012 as date but the column datatype is Varchar.

I want to convert it to 2012-03-20 00:00:00.000 as Datetime.

I tried using

CAST(CONVERT(CHAR(10), Column, 101) AS DATETIME)

But I get an error:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Complete code snippet to test:

DECLARE @Column VARCHAR(MAX) = '03202012'

SELECT CAST(CONVERT(CHAR(10), @Column, 101) AS DATETIME)
1
  • 1
    If you're on SQL Server 2008 or newer, I'd recommend to use DATE (if you need the date only - no time portion) or then DATETIME2(n) for date & time instead of DATETIME (which has a number of annoying issues). Commented Jan 5, 2016 at 5:51

3 Answers 3

3

Use yyyyMMdd format, that always works:

DECLARE @myDateString varchar(10) = '03202012';
SELECT cast( substring(@myDateString, 5, 4)+
             substring(@myDateString, 1, 2)+
             substring(@myDateString, 3, 2) AS datetime);
Sign up to request clarification or add additional context in comments.

1 Comment

I would be inclined to use left() and right(), but this is the better answer.
2

I found below script help me solved my concern.

SELECT convert(datetime, STUFF(STUFF('31012016',3,0,'-'),6,0,'-'), 105)

Result: 2016-01-31 00:00:00.000

Thanks all for the effort. :D

6 Comments

Is it okay to ask the question and post the answer by same person. I have never seen in SO @Ajay2707
There is no issue with that, only want to close the question by accepting any one answer.
@Ajay2707, how can i do that to close this question?
in each answer, below the down arrow there is right sign, click on it.
there's a label stating: You can accept your own answer in 2 days.
|
0

In MySQL, you can use the STR_TO_DATE function to convert a string to a date. For your example, it would look like this

STR_TO_DATE("03-02-2012", "%m-%d-%Y");

Note that the format part of the string must match the format part of the date.

Edit: Just found out this is for SQL Server, but I assume this will work there as well.

1 Comment

NO, it will not. Question is tagged with SQL Server and in such case no point in giving a MySQL specific answer. Isn't it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.