简体   繁体   English

SQL Server:从描述列中提取日期

[英]SQL Server: Extract date from a description column

how can I extract the dates from a description column (nvarchar) like these ones: 我如何从像这样的描述列(nvarchar)中提取日期:

'LICENCE SUSPENDED UNTIL DEC 17, 2016 - ABILITY IMPAIRED SUSPENSION NO 5176283'
'SUSPENDED FOR MEDICAL REASONS UNTIL JUNE 19, 2017'

The objective is to insert that date into a datetime column. 目的是将该日期插入datetime列。

I'm using SQL Server v17 我正在使用SQL Server v17

Thanks in advance :) 提前致谢 :)

edit: there is always an 'UNTIL' before the unstructured date. 编辑:非结构化日期之前始终有一个“ UNTIL”。

If dates are always in the same format and placed after UNTIL: 如果日期始终采用相同的格式,并放在“直到”之后:

WITH cte AS (
SELECT 'LICENCE SUSPENDED UNTIL DEC 17, 2016 - ABILITY IMPAIRED SUSPENSION NO 5176283' AS stringValue
UNION ALL SELECT 'SUSPENDED FOR MEDICAL REASONS UNTIL JUNE 19, 2017'
)

SELECT 
     CAST(SUBSTRING(stringValue, CHARINDEX('UNTIL', stringValue) + 5, CHARINDEX(', 20', cte.stringValue)-18)  AS DATE)
FROM cte

-- the output:

2016-12-17
2017-06-19

I used two anchors: 我使用了两个锚点:

  • 'UNTIL' to get into beginning of the date to parse “ UNTIL”进入要解析的日期的开始
  • ', 20' to detect the end of the date ',20'以检测日期的结束

I see a potential problem - months stated in different formats: DEC and JUNE.. My snippet still can handle this because of anchors, but it is a sign that the format of the string presentation of the date is not the same, therefore extra transformations perhaps required on larger dataset 我看到一个潜在的问题-月份以不同的格式表示:DEC和JUNE。.由于锚点,我的代码段仍然可以处理此问题,但这表明该日期的字符串表示形式不相同,因此需要进行额外的转换可能在较大的数据集上需要

Assuming there is just one date mentioned in nvarchar you need to extract and that it is always "UNTIL" word before that date as you said, you can try PATINDEX and SUBSTRING methods like below: 假设您需要提取nvarchar中提到的一个日期,并且该日期之前始终是“ UNTIL”字样,您可以尝试使用如下所示的PATINDEX和SUBSTRING方法:

DECLARE @x nvarchar(MAX) = N'SUSPENDED FOR MEDICAL REASONS UNTIL JUNE 19, 2017'
SELECT CONVERT(Date, substring(@x, patindex('%UNTIL%', @x) + 6, patindex('%[12][0-9][0-9][0-9]%', @x)-2 - patindex('%UNTIL%', @x)), 120)

SET @x  ='LICENCE SUSPENDED UNTIL DEC 17, 2016 - ABILITY IMPAIRED SUSPENSION NO 5176283'
SELECT CONVERT(Date, substring(@x, patindex('%UNTIL%', @x) + 6, patindex('%[12][0-9][0-9][0-9]%', @x)-2 - patindex('%UNTIL%', @x)), 120)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM