how can I extract the dates from a description column (nvarchar) like these ones:
'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.
I'm using SQL Server v17
Thanks in advance :)
edit: there is always an 'UNTIL' before the unstructured date.
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:
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
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:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.