简体   繁体   中英

sql - Extract a date from a string

I have a column description in my table with string value like this

"PK Event System Time: 31 January 2019 02:09  OK TO RIGOUR till 08:00 on Thursday Morning"

I need to extract the date part from this in SQL Server.

Expected output:

 31 January 2019 02:09

According to what you provide, you can simply use CHARINDEX() and SUBSTRING() functions as:

SELECT TRY_CAST(
       SUBSTRING(V, 
                 CHARINDEX(':', V)+2, 
                 CHARINDEX(':', V, CHARINDEX(':', V)+2) - CHARINDEX(':', V)+2
                ) AS DATETIME)
FROM
(
  VALUES
  ('PK Event System Time: 31 January 2019 02:09  OK TO RIGOUR till 08:00 on Thursday Morning'),
  ('Whatever: 01 Jun 2012 09:02  OK TO RIGOUR')
) T(V)

Note that the datetime should be always after ":". If it's not the case then please provide a good sample data.

Online Demo

The following works for your one example. I'm depending on the date starting after the first colon in the text string and then the time containing the second occurrence of a colon to locate the end of the date and time.

With TestValues AS
(
SELECT V.TextValue
FROM (VALUES
        ('PK Event System Time: 31 January 2019 02:09  OK TO RIGOUR till 08:00 on Thursday Morning')
     ) V(TextValue)

)
SELECT T.TextValue, TRY_CAST(DateString.DateString AS datetime) AS DateTimeVersion
FROM TestValues AS T
CROSS APPLY (SELECT NULLIF(CHARINDEX(':',T.TextValue),0) + 2 AS N) AS DateStart
CROSS APPLY (SELECT NULLIF(CHARINDEX(':',T.TextValue,DateStart.N),0) + 3 AS N) AS DateEnd
CROSS APPLY (SELECT SUBSTRING(T.TextValue,DateStart.N,DateEnd.N - DateStart.N) AS DateString) AS DateString

You can use CHARINDEX and SUBSTRING.

If "OK TO RIGOUR till" this String always present in your data then you check below query

select Trim( SUBSTRING(tbl.str, CHARINDEX(':',tbl.str) + 2 , (CHARINDEX('OK',tbl.str))  - (CHARINDEX(':',tbl.str) + 2))) from (SELECT V.str
FROM (VALUES
        ('PK Event System Time: 31 January 2019 02:09  OK TO RIGOUR till 08:00 on Thursday Morning')
     ) V(str)

  )tbl

http://sqlfiddle.com/#!18/9eecb/59559

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.

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