解析 SQL 中的日期

Parsing Dates in SQL

我的数据库中有一列当前是 varchar。数据如下所示:

Thu, 4 Jul 2013 09:18:24 
Thu, 11 Jul 2013 10:07:01
Tue, 28 Jan 2014 11:38:37
Fri, 26 Jul 2013 14:13:42

我希望能够将其转换为日期,以便获取最新记录。

假设字符串总是以三个字符的日字面量开头,后跟一个逗号和 space,例如,您可以使用 substring() 截断开头,然后使用 cast()将字符串转换为正确的日期时间,如下所示:

cast(substring(your_date_col, 6, len(your_date_col)) as datetime)

SQL Fiddle example

还有很多其他方法可以做到这一点;如果您想了解更多信息,请阅读 cast/convert 和字符串函数。 (并考虑改用 try_cast/try_convert)。

SQL Server 2012 以上,可以使用TRY_PARSE:

-- If the culture argument isn't provided, the language of current session is used.
SELECT TRY_PARSE('Thu, 4 Jul 2013 09:18:24' AS datetime2) AS 'datetime2'; 

TRY_PARSE: Returns the result of the expression, translated to the requested data type, or null if the cast fails.