Home Forums SQL Server 7,2000 T-SQL Need Split delimiter string into columns Solution RE: Need Split delimiter string into columns Solution

  • I just did something similar the other day with Progress arrays, which are returned to SQL Server as a single semicolon-delimited column, and I needed to split out one such array into several columns.

    This is the function I wrote... you would need to replace the semicolon ( with your own delimiter (a slash?).

    CREATE FUNCTION dbo.FromProgressArray (@array VARCHAR(4000), @index INT)

    RETURNS VARCHAR(4000)

    AS

    BEGIN

    IF @index = 0

    RETURN( LEFT(@array, CHARINDEX(';', @array) - 1) )

    DECLARE @counter INT

    SELECT @counter = 0

    WHILE @counter < @index

    BEGIN

    IF (CHARINDEX(';', @array) 0)

    SELECT @array = SUBSTRING(@array, CHARINDEX(';', @array) + 1, LEN(@array))

    ELSE

    SELECT @array = ''

    SELECT @counter = @counter + 1

    END

    IF CHARINDEX(';', @array) != 0

    SELECT @array = LEFT(@array, CHARINDEX(';', @array) - 1)

    RETURN( @array )

    END

    GO

    Then you can do this:

    INSERT INTO table (cat, subcat1, subcat2, subcat3, subcat4, subcat5)

    SELECT dbo.FromProgressArray(sourcecol, 0), dbo.FromProgressArray(sourcecol, 1), dbo.FromProgressArray(sourcecol, 2), dbo.FromProgressArray(sourcecol, 3), dbo.FromProgressArray(sourcecol, 4), dbo.FromProgressArray(sourcecol, 5)

    FROM source_table

    HTH.