Convert dd/mm/yyyy to date in SQL Server

痴心易碎 提交于 2020-01-04 06:06:32

问题


I'm going nuts trying to convert a string type column into date.

The column name is StartDate, which contains a string date format dd/mm/yyyy. The field type is varchar(3000).

I tried the following:

CONVERT(datetime, StartDate, 103)

CAST(CONVERT(VARCHAR(10), StartDate, 110) AS DATE)

CONVERT(DATE, RIGHT(StartDate, 4) + '-' + SUBSTRING(StartDate, 4, 2) + '-' + LEFT(StartDate, 2), 126)

and other similar combinations.

I keep getting "out of range" and "conversion failed" error messages.

Does anyone have a creative solution?


回答1:


I suspect you have some bogus data. For example

 Select try_convert(date, '15/07/2014', 103)

Returns

2014-07-15

If 2012+, I would suggest that you

Select *
 From YourTable
 Where try_convert(date, StartDate, 103) is null

This will identify your problem areas



来源:https://stackoverflow.com/questions/43765695/convert-dd-mm-yyyy-to-date-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!