Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in SQL by (20.3k points)

I’m looking to split '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15...' (comma delimited) into a table or table variable.

Does anyone have a function that returns each one in a row?

1 Answer

0 votes
by (40.7k points)

Try using the below code:

DECLARE @xml xml, @str varchar(100), @delimiter varchar(10)

SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'

SET @delimiter = ','

SET @xml = cast(('<X>'+replace(@str, @delimiter, '</X><X>')+'</X>') as xml)

SELECT C.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as X(C)

Otherwise you can use this:

DECLARE @str varchar(100), @delimiter varchar(10)

SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'

SET @delimiter = ','

;WITH cte AS

(

    SELECT 0 a, 1 b

    UNION ALL

    SELECT b, CHARINDEX(@delimiter, @str, b) + LEN(@delimiter)

    FROM CTE

    WHERE b > a

)

SELECT SUBSTRING(@str, a,

CASE WHEN b > LEN(@delimiter) 

    THEN b - a - LEN(@delimiter) 

    ELSE LEN(@str) - a + 1 END) value      

FROM cte WHERE a > 0

Related questions

0 votes
1 answer
asked Jul 23, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...