将字符串转换成这种特定的日期格式?

Convert character string into this specific date format?

我正在使用 SQL Server 2014 并且我有一个 table (t1),其中包含 nvarchar 格式的列 (ReviewDate)。

该列的一行示例如下:

       ReviewDate
  Mr John wrote a review in Oct 2017

我需要从这个字符串中提取 "date" 部分。

为此,我的T-SQL如下:

SELECT (RIGHT([ReviewDate], 8)) as [ReviewDate 2]
FROM t1

这给了我 "Oct 2017"。

现在,我想将 "Oct 2017" 转换为“2017-10-01”作为 datetime 格式。这就是我卡住的地方。

我尝试了以下方法:

SELECT CONVERT(datetime, (RIGHT([ReviewDate], 8)), 121) as [ReviewDate2]

以上语法给出了以下错误消息:"Conversion failed when converting date and/or time from character string."

SELECT CAST( (RIGHT([ReviewDate], 8)) as datetime) as [ReviewDate2]

以上语法给出了相同的错误信息:

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

我们将不胜感激。

到目前为止,当我尝试转换时,您的示例文本是 mssql 中的有效日期时间。您的 table 上似乎有一些无效数据。尝试使用 try_cast() 来包含那些无效数据。

declare @ReviewDate varchar(max)='Mr John wrote a review in Oct 2017'

set  @ReviewDate = (RIGHT(@ReviewDate, 8))

select try_cast(@ReviewDate as datetime) as [ReviewDate2]

dbfiddle<>

你所有的查询都是正确的,但要确保除了日期部分之外,它不应该有任何其他字符串。

For example SELECT CAST('x Oct 2017' AS DATE) 会给你

这样的错误

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

SELECT CAST((RIGHT('Mr John wrote a review in Oct 2017', 8)) as datetime) as [ReviewDate2]
SELECT CAST('Oct 2017' AS DATE)
SELECT CONVERT(DATETIME, 'Oct  2017 ', 121) as [ReviewDate2]

FIDDLE DEMO