Introduction
This is another version of token splitting UDF for SQL Server. I needed to split "Token1=Value1|Token2=Value2|Token3=Value3
" into components, and created a function based on the one proposed by Irfan Baig.
ALTER FUNCTION dbo.Split2 (@String varchar(8000), @TokenDelimiter varchar(10), @ValueDelimiter varchar(10))
RETURNS @Tokens TABLE (Token varchar(255), Value varchar(255))
AS
BEGIN
DECLARE @TokenValue varchar(1000), @p int
WHILE @String <> '' BEGIN
SET @p = CHARINDEX(@TokenDelimiter, @String)
IF @p > 0 BEGIN
SET @TokenValue = LTRIM(RTRIM(LEFT(@String, @p-1)))
SET @String = LTRIM(RTRIM(RIGHT(@String, LEN(@String) - @p - LEN(@TokenDelimiter) + 1)))
END
ELSE BEGIN
SET @TokenValue = @String
SET @String = ''
END
SET @p = CHARINDEX(@ValueDelimiter, @TokenValue)
IF @p > 0 BEGIN
INSERT @Tokens (Token, Value)
SELECT
Token = LTRIM(RTRIM(LEFT(@TokenValue, @p-1)))
,Value = LTRIM(RTRIM(RIGHT(@TokenValue, LEN(@TokenValue) - @p - LEN(@ValueDelimiter) + 1)))
END
END
RETURN
END
GO