There are several SQL split functions, from loop driven, to using xml commands, and even using a numbers table. I haven\'t found one that supports text qualifiers.
Usin
Here is my solution:
CREATE FUNCTION fnSplitString
(
@input nvarchar(MAX)
)
RETURNS @emails TABLE
(
email nvarchar(MAX)
)
AS
BEGIN
DECLARE @len int = LEN(@input)
DECLARE @pos int = 1;
DECLARE @start int = 1;
DECLARE @ignore bit = 0;
WHILE(@pos<=@len)
BEGIN
DECLARE @ch nchar(1) = SUBSTRING(@input, @pos, 1);
IF ( @ch = '"' or @ch = '''')
BEGIN
SET @ignore = 1 - @ignore;
END
IF (@ch = ',' AND @ignore = 0)
BEGIN
INSERT @emails VALUES (SUBSTRING(@input, @start, @pos-@start));
SET @start = @pos+1;
END
SET @pos = @pos + 1;
END
IF (@start<>@pos)
BEGIN
INSERT @emails VALUES (SUBSTRING(@input, @start, @pos-@start));
END
RETURN
END
GO
DECLARE @input nvarchar(max) = 'jsmith@anywhere.com, "Sally \"Heat\" Jones" , "Mark Jones" , "Stone, Ron" ';
select * from fnSplitString(@input)