简体   繁体   中英

Extracting a specific string from a column based on other column using SQL in SQL server 2008

I have two columns in a table. Both are nvarchar of different lengths, let's say first columns contains the color (representing a country) and other column contains the country name with other text eg

Color      text 
green      choosen country: UNITED STATES *some text no fixed length upto 1000 chars*
black      chossen country: S AFRICA *some text no fixed length upto 1000 chars*
red        choosen country: INDIA *some text no fixed length upto 1000 chars*

Now I want color and the country name concatenated in my output, as

green,UNITED STATES
black,S AFRICA
red,INDIA

You can extract the country name as from your example:

select stuff(text, 1, charindex(': ', text + ': ') + 2, '') as country_name

You can concatenate anything else you want as:

select color + ',' + stuff(text, 1, charindex(': ', text + ': ') + 2, '') as country_name

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