0

How can I get each value of a column that has a comma separator in her value ?

Example:

ID   ColumnUnified
1    12,34,56,78
2    80,99,70,56

What I want is a query to get the number without comma. If possible, in collumns.

12    34     56    78
Lucas_Santos
  • 4,638
  • 17
  • 71
  • 118

2 Answers2

0

This will work for any number of values http://beyondrelational.com/modules/2/blogs/70/posts/10844/splitting-delimited-data-to-columns-set-based-approach.aspx

Madhivanan
  • 13,470
  • 1
  • 24
  • 29
0

The solution Madhivanan's link refers to is very creative, but I had a slight problem with it on SQL Server 2012 related to the name of one of the columns (Start). I've modified the code in his answer to use StartPos instead of Start for the column name.

I was not familiar with the system procedure spt_values, but I found a very informative description of the procedure here on SO for those who are interested in exactly how this solution works.

Finally, here's the (slightly) revised code from Madhivana's answer:

CREATE TABLE #test(id int, data varchar(100))

INSERT INTO #test VALUES (1,'This,is,a,test,string')
INSERT INTO #test VALUES (2,'See,if,it,can,be,split,into,many,columns')

DECLARE @pivot varchar(8000)
DECLARE @select varchar(8000)

SELECT  @pivot = COALESCE(@pivot + ',', '') + '[col'
        + CAST(number + 1 AS VARCHAR(10)) + ']'
FROM    master..spt_values
WHERE   type = 'p'
        AND number <= ( SELECT  MAX(LEN(data) - LEN(REPLACE(data, ',', '')))
                        FROM    #test
                      )

SELECT  @select = '
    select p.*
    from (
    select
    id,substring(data, StartPos+2, endPos-StartPos-2) as token,
    ''col''+cast(row_number() over(partition by id order by StartPos) as varchar(10)) as n
    from (
    select
    id, data, n as StartPos, charindex('','',data,n+2) endPos
    from (select number as n from master..spt_values where type=''p'') num
    cross join
    (
    select
    id, '','' + data +'','' as data
    from
    #test
    ) m
    where n < len(data)-1
    and substring(data,n+1,1) = '','') as data
    ) pvt
    Pivot ( max(token)for n in (' + @pivot + '))p'

EXEC(@select)

DROP TABLE #test
Community
  • 1
  • 1
Tim Lentine
  • 7,782
  • 5
  • 35
  • 40