I have created a stored procedure to attempt to replicate the split_string function that is now in SQL Server 2016.
So far I have got this:
CREATE FUNCTION MySplit
(@delimited NVARCHAR(MAX), @delimiter NVARCHAR(100))
RETURNS @t TABLE
(
-- Id column can be commented out, not required for SQL splitting string
id INT IDENTITY(1,1), -- I use this column for numbering split parts
val NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @xml XML
SET @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'
INSERT INTO @t(val)
SELECT
r.value('.','varchar(max)') AS item
FROM
@xml.nodes('//root/r') AS records(r)
RETURN
END
GO
And it does work, but it will not split the text string if any part of it contains an ampersand [ & ].
I have found hundreds of examples of splitting a string, but none seem to deal with special characters.
So using this:
select *
from MySplit('Test1,Test2,Test3', ',')
works ok, but
select *
from MySplit('Test1 & Test4,Test2,Test3', ',')
does not. It fails with
XML parsing: line 1, character 17, illegal name character.
What have I done wrong?
UPDATE
Firstly, thanks for @marcs, for showing me the error of my ways in writing this question.
Secondly, Thanks to all of the help below, especially @PanagiotisKanavos and @MatBailie
As this is throw away code for migrating data from old to new system, I have chosen to use @MatBailie solution, quick and very dirty, but also perfect for this task.
In the future, though, I will be progressing down @PanagiotisKanavos solution.
'&' with'&', just like in normal use of html/xml? Then, once split, convert it back again?FOR XMLto get around this type of issue...FOR XMLis used for string aggregation. In this case there is only a string that gets converted to an XML by replacing the delimiter with'</r><r>'. The only solution here is to escape invalid characters