Split Any Delimited String in SQL






4.83/5 (3 votes)
This is an alternative for "Split Any Delimited String in SQL"
It's still not a very good solution ("any" is most inaccurate), but here's a Recursive Common Table Expression way to do it.
CREATE FUNCTION dbo.fnSimpleSplit
( @InputString NVARCHAR(MAX)
, @Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
-- SELECT * FROM dbo.fnSimpleSplit ( 'Apple, Mango, Orange, Pineapple' , ',' )
WITH cte AS
(
SELECT CAST(NULL AS NVARCHAR(MAX)) val , @InputString + @Delimiter s , CHARINDEX(@Delimiter,@InputString) offset
UNION ALL
SELECT SUBSTRING(s,1,offset-1) , SUBSTRING(s,offset+1,LEN(s)) , CHARINDEX(@Delimiter,s,offset+1)-offset
FROM cte
WHERE offset>0
)
SELECT val
FROM cte
WHERE val IS NOT NULL
)