-3

I work on sql server 2017 I have table name #countriesData data as below

my issue here How to convert countries column data separated pipe to rows .

meaning every rev and company and year will have only one country per row .

   create table #countriesData
 (
 company int,
 [Year] int,
 rev  int,
 countries varchar(500)
 )
 insert into #countriesData(company,[Year],rev,countries)
 values
 (12011,2010,121,'Egypt|France|America'),
 (12011,2011,121,'Egypt|Canda|America'),
 (12011,2012,121,'China|Canda|America'),
 (12099,2010,121,'SaudiArabia|France|America'),
 (12099,2011,121,'Egypt|Canda|German'),
 (12099,2012,121, 'China|Italy|America')

my expected result will be as below : picture for pipe separated rows

suppose i have two columns have pipe so how to modify query to handle two columns have pipe on same time

 create table #countriesData
 (
 company int,
 [Year] int,
 rev  int,
 countries varchar(500),
 countries1 varchar(500)
 )
 insert into #countriesData(company,[Year],rev,countries,countries2)
 values
 (12011,2010,121,'Egypt|France|America','India|France|America'),
 (12011,2011,121,'Egypt|Canda|America','India|Indonisya|America'),
 (12011,2012,121,'China|Canda|America','Pakistan|Indonisya|America'),
 (12099,2010,121,'SaudiArabia|France|America','Pakistan|sryia|America'),
 (12099,2011,121,'Egypt|Canda|German','Pakistan|Saudia|America'),
 (12099,2012,121, 'China|Italy|America','Holanda|Saudia|America')
1
  • 2
    The stick character | is called as pipe. One can split the string, what would you like to do with the data later on?
    – vonPryz
    Commented May 23, 2022 at 9:42

1 Answer 1

1

The problem here is that you have violated 1NF by storing multiple values in a single tuple. You are going to have to parse this into rows. You can use the built in STRING_SPLITfor this.

select *
from #countriesData c
cross apply STRING_SPLIT(c.countries, '|') x
2
  • i updated post i need to make same thing that i make for column countries for two columns countries and countries2 Commented May 24, 2022 at 17:20
  • Your table design is so utterly broken. Just take the query I posted above with one of your delimited columns. Then use UNION ALL to combine that with a second query that uses the second of your delimited columns. Then go back and fix your table structure and stop storing delimited data like this.
    – Sean Lange
    Commented May 24, 2022 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.