0

I have a table that contains:

ID     Names 
1      Aaron, Betsy, Cindy 
2      Dillon, Eric, Fred 

I would like to parse through the name column and have it return:

ID   Names 
1    Aaraon 
1    Betsy 
1    Cindy 
2    Dillon 

I have found several functions online that parse the names column but does not tie the ID back to it.

7
  • Is there a particular reason you don't already have a one-to-many relationship modeled? Or is this query part of your plan to migrate to a proper one-to-many relationship? Commented Jan 4, 2013 at 0:08
  • 3
    what rdbms you are using? mysql? oracle? sql server?... Commented Jan 4, 2013 at 0:08
  • What RDBMS are you using? Commented Jan 4, 2013 at 0:08
  • When confronted by problems like this and there isn't a function in the rdbms you are using, you can either write that function yourself or bring the result set into your client program and post-process the results locally. For small data sets, I sometimes reach for the latter since it can be simpler. Commented Jan 4, 2013 at 0:30
  • What's the example that you found that returns the names but not the id? Commented Jan 4, 2013 at 0:30

1 Answer 1

2

How about something like this:

;with cte (id, name, names) as
(
  select id,
    cast(left(names, charindex(',',names+',')-1) as varchar(50)) name,
         stuff(names, 1, charindex(',',names+','), '') names
  from yourtable
  union all
  select id,
    cast(left(names, charindex(',',names+',')-1) as varchar(50)) name,
    stuff(names, 1, charindex(',',names+','), '') names
  from cte
  where names > ''
) 
select id, name
from cte
order by id

See SQL Fiddle with Demo

Returns the result:

| ID |   NAME |
---------------
|  1 |  Aaron |
|  1 |  Betsy |
|  1 |  Cindy |
|  2 | Dillon |
|  2 |   Eric |
|  2 |   Fred |
Sign up to request clarification or add additional context in comments.

1 Comment

@user1411074 Happy to help. If this answer is helpful to you then be sure to accept via the checkmark on the left. It will help future visitors to the site and you get reputation for accepting.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.