Introduction
Write a table
function to split a string
with specific separator character.
Example:
SELECT * FROM dbo.Split('john, peter, mary', ',')
And result:
CREATE FUNCTION [dbo].[Split](@array NVARCHAR(MAX),@separator char(1))
RETURNS @tbl TABLE (string nvarchar(128) NOT NULL) AS
BEGIN
DECLARE @pos int,
@textpos int,
@chunklen smallint,
@str nvarchar(MAX),
@tmpstr nvarchar(MAX),
@leftover nvarchar(MAX)
SET @textpos = 1
SET @leftover = ''
WHILE @textpos <= datalength(@array) / 2
BEGIN
SET @chunklen = 4000 - datalength(@leftover) / 2
SET @tmpstr = ltrim(@leftover + substring(@array, @textpos, @chunklen))
SET @textpos = @textpos + @chunklen
SET @pos = charindex(@separator, @tmpstr)
WHILE @pos > 0
BEGIN
SET @str = substring(@tmpstr, 1, @pos - 1)
INSERT @tbl (string) VALUES(convert(nvarchar(20), @str))
SET @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
SET @pos = charindex(@separator, @tmpstr)
END
SET @leftover = @tmpstr
END
IF ltrim(rtrim(@leftover)) <> ''
INSERT @tbl (string) VALUES(convert(nvarchar(Max), @leftover))
RETURN
END
GO