简体   繁体   中英

I Want to extract time from a string

String Example:

DH      SG 136      BOM      (20:15)       (22:20)      DEL  FLT     SG 11       DEL      (08:55)       (12:50)      DXB  FLT     SG 14       DXB      (14:00)       (16:55)      BOM  

My Query is:

 select
 right (substring(previousdata,0,charindex(':',previousdata)+1),3)+
 left(substring(previousdata,charindex(':',previousdata)+1, len(previousdata)),2) as TimeSt,
  PreviousData from com.NOTIFICATIONHISTORY

the problem is it is also extracting non numeric values back and forth semicolon: i want only time.. very first 'time' mentioned in string

It looks like the timestamps in the string have leading zeroes (so 01:15, not 1:15) and something like the following should work:

select SUBSTRING(X, PATINDEX('%[0-9][0-9]:[0-9][0-9]%', X), 5)

Test:

select
SUBSTRING(X, PATINDEX('%[0-9][0-9]:[0-9][0-9]%', X), 5)
, X
from
(select 
 'DH      SG 136      BOM      (20:15)       (22:20)      DEL  FLT     SG 11       DEL      (08:55)       (12:50)      DXB  FLT     SG 14       DXB      (14:00)       (16:55)      BOM  
 ' AS x UNION SELECT 
 'DH: SG 282 MAA-AMD 12:13 28-Nov-2013 14:38 28-Nov-2013, FLT :SG 345 AMD-PNQ 21:34 22:55, FLT :SG 345 PNQ-BLR 23:39 01:05
 ' AS x ) data

Result:

(No column name)    X
20:15   DH      SG 136      BOM      (20:15)       (22:20)      DEL  FLT     SG 11       DEL      (08:55)       (12:50)      DXB  FLT     SG 14       DXB      (14:00)       (16:55)      BOM     
12:13   DH: SG 282 MAA-AMD 12:13 28-Nov-2013 14:38 28-Nov-2013, FLT :SG 345 AMD-PNQ 21:34 22:55, FLT :SG 345 PNQ-BLR 23:39 01:05   

Perhaps you were making this requirement more complex than it needs to be. Just take the first five characters after the first occurrence of ( :

SELECT SUBSTRING(col, CHARINDEX('(', col) + 1, 5)
FROM yourTable;

Demo

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