简体   繁体   中英

How to extract the specific part of string in SQL server?

I have a string ST0023_Lamb_Weston_2017_US in a table from particular column. While selecting the name I need to get only Lamb_Weston_2017_US . I can use

SELECT SUBSTRING('ST0023_Lamb_Weston_2017_US', 8, 20)

But there will be different names in the column. For example,

ST0023_Lamb_Weston_2017_US
ST0053_PL_Sandbox_Dorgan_US
ST0071_EDA_Austria
ST0071_EDA_Austria
ST10338_Nestle_Soluble_Instant_Cacao_ES

So the above mentioned are the different names available. I need to remove the "ST" part and the number part till first hyphen and return name alone. Please help me with this.

Inside substring function use charindex to pick the starting position of underscore. Plus one is added with charindex to exclude the underscore position and ending position will be considered till the length of the data.

create table data
(
value varchar(100)
)

insert into  data
select 'ST0023_Lamb_Weston_2017_US' union 
select 'ST0053_PL_Sandbox_Dorgan_US' union
select  'ST0071_EDA_Austria'  union
select  'ST0071_EDA_Austria' union
select 'ST10338_Nestle_Soluble_Instant_Cacao_ES' 
go
select value, SUBSTRING(value, CHARINDEX('_',value)+1 , LEN(value)) 'Newvalue' from data 

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