简体   繁体   中英

Extract values from column in SQL Server

How to extract the following values from a column in SQL Server:

"ICMP (type: 8 / subtype: 0)" -----> "8" and "0"
"ICMP (type: 0 / subtype: 19)" -----> "0" and "19"
"ICMP (type: 11 / subtype: 5)" -----> "11" and "5"
"ICMP (type: 12 / subtype: 30)" -----> "12" and "30"

I tried different functions - charindex(), left(), right() but I failed.

SQL Server is not great at string manipulation. But cross apply helps a bit:

select left(v.str1, charindex(' ', v.str1)) as type, replace(v.str2, ')', '') as subtype
from (values ('ICMP (type: 8 / subtype: 0)'), ('ICMP (type: 12 / subtype: 30)')) t(field) cross apply
     (values ( stuff(field, 1, charindex('type:', field) + 5, ''),
               stuff(field, 1, charindex('subtype:', field) + 8, '')
             )
     ) v(str1, str2);

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