I have a table that contains a Date column in varchar format. The date format varies since it’s the date format of a computer that used our program. For example, I have the following formats:
- 10.7.2010
- 7/11/2010 7:36:55 AM
I’ve tried using:
SELECT CONVERT(DateTime, Date, 103) AS Expr1
FROM MyTable
But I get an out-of-range datetime value exception for the following line:
7/13/2010 3:33:45 PM
I need a way to convert those values to a unified format. Time and the output format are not important, as long as it’s comparable (when copied to Excel or something. It’s to be used externally, so I don’t mind not changing the actual values in the DB).
The database is MSSQL 2005.
You need to read up on MSDN Books Online – topic: CAST and CONVERT.
This shows you all the possible, supported date formats, e.g.
will convert today’s date into ISO format and you’ll get
20110707as the output.For maximum compatibility, I would recommend the ISO-8601 date format:
or
Those always work, can always be converted, regardless of your SQL Server’s date, regional and language settings…
Update:
Converting your existing strings into
DATEorDATETIMEdepends heavily on your language/regional settings:Result here is:
Dates are interpreted as 7th of October 2010, 11th of July 2011 and 13th of July 2010
Result here is:
Dates are interpreted as tenth of July 2010 and 7th of November 2011
And of course, converting
@string3to a date with these settings will fail, since it’s trying to interpret it as 7th of the 13th month ….. and there is no 13th month…..Because of such ambiguities, I would recommend to always use the ISO-8601 formats, which are clear, standardized, always work, and it’s always defined what date is really represented.
Update #2:
Of course, you could also use the
ISDATE()function check if a given string can be interpreted as a valid date:In the case of
SET DATEFORMAT DMY, the string value of'7/13/2010 3:33:45 PM'will be recognized as invalid:returns
0as its value.