I want to split a string by replacing the spaces with xml tags in sql. I have a user defined function as follows:
CREATE FUNCTION [dbo].[stringtoxml]
(
@string_to_split NVARCHAR(MAX),
@delimiter NVARCHAR(100)
)
RETURNS XML
AS
BEGIN
DECLARE @xml XML
SET @xml = N'<t>' + REPLACE(@string_to_split, @delimiter,'</t><t>') + '</t>'
RETURN @xml
END
I'm storing the xml in a field employee_name with a datatype of xml. In another table, I want to be able to read the first element as the first name, second element as the middle initial if the format is one alpha character followed by a full stop and the third element as the last name.
There are invalid characters in the @string_to_split - for example 'John O'Smith'.
Is there a way to get around the invalid characters without having to do:
DECLARE @xml XML
SET @xml = N'<t>' + REPLACE(REPLACE(REPLACE(@string_to_split,'''','''),'&','&'), @delimiter,'</t><t>') + '</t>'
RETURN @xml
and then to do another replace to remove &apos and & when I'm reading the individual elements in the other table.
TSQLforSQL-Server? Please tag the question appropriately. It makes a difference, as different database engines have different string/XML handling capabilities.