Split column values up into different columns

  • Hi Guys

    I have a column which has data a,b,c,d,e,f

    I need to split the data after every comma to put into the other columns in the table so I would have column 1 = a column 2 = b etc etc.

    How would I do that?

    Thanks

  • Try this..

    Drop function CutCsv

    go

    Create function CutCsv(@CSVString varchar(max))

    returns table

    as

    return(

    with Num1 (n) AS (SELECT 1 UNION ALL SELECT 1),

    Num2 (n) AS (SELECT 1 FROM Num1 AS X, Num1 AS Y),

    Num3 (n) AS (SELECT 1 FROM Num2 AS X, Num2 AS Y),

    Num4 (n) AS (SELECT 1 FROM Num3 AS X, Num3 AS Y),

    Nums (n) AS (SELECT ROW_NUMBER() OVER(ORDER BY n) FROM Num4),

    SpacesPos(sIndex)

    as

    (

    Select n+1

    from nums

    where n spacesPos.SIndex)-1

    from spacesPos

    )

    Select Item = ltrim(rtrim(substring(@CSVString,StartPos,(EndPos-StartPos))))

    from cteSpaceDelta

    where EndPos is not null

    )

    go

    Select * from dbo.CutCsv('10,2,2,2,4,4,5')



    Clear Sky SQL
    My Blog[/url]

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply