Friday, January 25, 2013

SQL Function to Split a varchar Field

I've found on the web but I cannot remember where, a very usefull SQL Function used to strip an input string. Return parameter is a table.

CREATE FUNCTION [dbo].[Split] (@s varchar(512), @sep char(1))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
      WHERE stop > 0
    )
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces
  )

The limit of this function is that you cannot use OPTION (MAXRECURSION nnn) to change default 100 limit in SQL recusrsion.

No comments: