4
Select CONVERT(Date, '13-5-2012')

When i run the above T-SQL statement in Management Studio, i get i get the following error:

"Conversion failed when converting date and/or time from character string"

Is there away i can cast that value to a valid Date type successfully? I have such values in a nvarchar(255) column whose dataType i want to change to Date type in an SQL Server table but i have hit that error and i would like to first do a conversion in an Update statement on the table.

5 Answers 5

11

Specify what date format you are using:

Select CONVERT(Date, '13-5-2012', 105)

105 means Italian date format with century (dd-mm-yyyy).

Ref: http://msdn.microsoft.com/en-us/library/ms187928.aspx

Sign up to request clarification or add additional context in comments.

Comments

4

In general, I'd suspect usually there is data which can't be converted in a column, and would use a case statement checking it's convertable first:

SELECT CASE WHEN ISDATE(mycolumn)=1 THEN CONVERT(Date, mycolumn, [style]) END
FROM mytable

I believe Convert relies on the SQL Server date format setting. Please check your dateformat setting with DBCC USEROPTIONS.

I suspect if you set the dateformat to dmy it'll understand:

SET DATEFORMAT dmy
GO

If even then it doesn't work, you can't find a style that matches your data, and if your data is in a consistant format, it's down to manual string manipulation to build it (don't do this if you can help it).

Comments

0

Try this....

Select CONVERT(Date,'5-13-2012')

Use 'mm-dd-yyyy' format.

1 Comment

i have tested that, it works but i have a few hundred rows in a table with values in '13-5-2012' format in a column, i want to change the datatype of that column from nvarchar(255) to Date but its not accepting because of the '13-5-2012' values. So i want to run an update statement that will convert '13-5-2012' to '5-13-2012'
0

CONVERT assumes that the original data can represent a date. One bad data item can throw the same conversion error mentioned here without pointing to the problem.

Using ISDATE helped me get around the bad data items.

SELECT CONVERT(DATE, CONVERT(CHAR(8), FieldName)) FROM DBName WHERE ISDATE(FieldName) <> 0

Comments

0

You need to give the date format while conversion, this will resolve the error.

select convert(date, '13-5-2012' ,103)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.