我有一张包含以下内容的表:
ID Names
1 Aaron, Betsy, Cindy
2 Dillon, Eric, Fred
我想解析名称列并让它返回:
ID Names
1 Aaraon
1 Betsy
1 Cindy
2 Dillon
我在网上发现了几个解析名称列的函数但没有将ID绑定到它。
答案 0 :(得分:2)
这样的事情怎么样:
;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
返回结果:
| ID | NAME |
---------------
| 1 | Aaron |
| 1 | Betsy |
| 1 | Cindy |
| 2 | Dillon |
| 2 | Eric |
| 2 | Fred |