Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / algorithm

Split Any Delimited String in SQL

4.83/5 (3 votes)
11 Sep 2015CPOL 14.6K  
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.
SQL
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
)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)