使用SQL Server将分隔的字符串转换为表

时间:2013-03-11 09:31:29

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我有2列

ID          value
---      ----------
1        "1,abc,,3"
2        "2,qwe,the,4"

如何将分隔值转换为表格

即:

col1         col2        col3       col4
-----        -----       -----      ----
1            abc                      3
2            qwe         the          4       

希望尽快获得一些帮助。提前谢谢..

1 个答案:

答案 0 :(得分:1)

根据您的问题,这只是4列的示例。这可以概括为:

with cte as(
SELECT id,CHARINDEX(',', value) First_occurence,

CHARINDEX(',', value, CHARINDEX(',', value)+1) Second_occurrence,

CHARINDEX(',', value, CHARINDEX(',', value, CHARINDEX(',', value)+1)+1) Third_occurrence

from test)

select  substring(value,1,first_occurence-1) col1,
substring(value,first_occurence+1,Second_occurrence-(first_occurence+1)) col2,
substring(value,Second_occurrence+1,Third_occurrence-(Second_occurrence+1)) col3,
substring(value,Third_occurrence+1,len(value)) col4

from test a
inner join 
cte b
on a.id=b.id

广义:

Declare @col_count  int=1

;with cte as(
SELECT id, @col_count col,value,CHARINDEX(',', value) occurence,substring(value,1,CHARINDEX(',', value)-1) col_val from test

  union all
select id, col+1 col,value, CHARINDEX(',', value, occurence+1),
  substring(value,occurence+1,CHARINDEX(',', value, occurence+1)-(occurence+1))

  from cte
 where  (occurence+1)< len(value)
union all

select id, col+1 col,value, occurence+1,
  substring(value,occurence+1,len(value))
  from cte
 where  (occurence+1)= len(value)
)



SELECT [1], [2], [3], [4]
from
(
  SELECT col, col_val,
    row_number() over(partition by col order by col_val) rn
  from cte
) as st
pivot
(
  max(col_val)
  FOR col in ([1], [2], [3], [4])
) as pivottable

只需添加[5],[6],....即可获得最终select中的更多列。

SQL Fiddle