alix-o
1/29/2014 - 9:45 PM

Function to parse a delimited string and return a table

Function to parse a delimited string and return a table

CREATE FUNCTION fnParseString (@string NVARCHAR(MAX),@separator NCHAR(1))
RETURNS @parsedString TABLE (string NVARCHAR(MAX))
AS 
BEGIN
   DECLARE @position int
   SET @position = 1
   SET @string = @string + @separator
   WHILE charindex(@separator,@string,@position) <> 0
      BEGIN
         INSERT into @parsedString
         SELECT substring(@string, @position, charindex(@separator,@string,@position) - @position)
         SET @position = charindex(@separator,@string,@position) + 1
      END
     RETURN
END
 --declare a table where the parsed values can be stored
 DECLARE @ParsedStringTable TABLE
 (
    --set a column named "Source"
    Source varchar(20)
 )
 

INSERT INTO @ParsedStringTable
    -- pass delimited string and delimter into function (CKI+FEE+IHS, '+')
    -- Select the string table returned from the function (line 2)
    SELECT string FROM dbo.fnParseString (@DelimitedStringParameter , ''+'')'