在sqlserver中分隔单个列的值

时间:2012-02-27 12:20:02

标签: sql-server-2005

我在一个问题表中有一个名为categoryid的字段,该字段可以输入多个值来显示不同的类别。 现在我想分开每个值并单独获取它。

值由字符

分隔

例如

categoryid varchar
3
3,8
5,9,7
8,5,7,3,2

如何使用sql查询分隔每个? 请帮忙

1 个答案:

答案 0 :(得分:1)

declare @T table
(
  category_id varchar(10)
)

insert into @T
select '3' union all
select '3,8' union all
select '5,9,7' union all
select '8,5,7,3,2'

;with C(ID, category_id) as
(
  select cast(left(category_id, charindex(',', category_id+',', 1)-1) as int),
         stuff(category_id, 1, charindex(',', category_id+',', 1), '')
  from @T
  union all
  select cast(left(category_id, charindex(',', category_id+',', 1)-1) as int),
         stuff(category_id, 1, charindex(',', category_id+',', 1), '')
  from C
  where len(category_id) > 0
)
select ID
from C
相关问题