我有一个表,其中包含:
ID Names
1 Aaron, Betsy, Cindy
2 Dillon, Eric, Fred
我想解析 name 列并让它返回:
ID Names
1 Aaraon
1 Betsy
1 Cindy
2 Dillon
我在网上找到了几个解析名称列但不将 ID 绑定回它的函数。
我有一个表,其中包含:
ID Names
1 Aaron, Betsy, Cindy
2 Dillon, Eric, Fred
我想解析 name 列并让它返回:
ID Names
1 Aaraon
1 Betsy
1 Cindy
2 Dillon
我在网上找到了几个解析名称列但不将 ID 绑定回它的函数。
像这样的东西怎么样:
;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 |