Monday, January 12, 2009

Sql Split function

CREATE FUNCTION Split

(

     @StringToSplit varchar(2048),

     @Separator varchar(128)

)

RETURNS TABLE AS RETURN

WITH CTE AS

(

     SELECT 0 StartIndex, 1 EndIndex

     UNION ALL

     SELECT EndIndex, CHARINDEX(@Separator, @StringToSplit, EndIndex) + LEN(@Separator)

     FROM CTE

     WHERE EndIndex > StartIndex

)

SELECT

     SUBSTRING(@StringToSplit

                        , StartIndex

                        , CASE WHEN EndIndex > LEN(@Separator)

                                  THEN EndIndex-StartIndex-LEN(@Separator)

                                  ELSE LEN(@StringToSplit) - StartIndex + 1

                         END) String

     ,StartIndex StartIndex     

FROM CTE

WHERE StartIndex > 0

No comments: