1. 程式人生 > >SQL SERVER 字元拆分列為多行

SQL SERVER 字元拆分列為多行

注:先學習sql server裡的遞迴CTE。

假設有興趣表Hobbys

Name Hobby
小張 籃球,足球,羽毛球

 

 

 

Name Hobby
小張 籃球
小張 足球
小張 羽毛球

 

 

 

 

 

採用【遞迴cte】

with tempHobbys as
(select Name,Hobby,charindex(',',Hobby)-1 endindex,0 startindex from Hobbys union all select Name,Hobby,charindex(',',Hobby,endindex+2)-1 endindex,endindex+2 startindex from tempHobbys where endindex>-1), with tempHobbys 2 as (select Name,Hobby,(case when endindex<0 then len(Hobby) else Hobby end
) endindex,startindex from tempHobbys) select Name,substring(Hobby,startindex,endindex-startindex+1) Hobby from tempHobbys2