1

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,'''','&apos;'),'&','&amp;'), @delimiter,'</t><t>') + '</t>'
RETURN @xml

and then to do another replace to remove &apos and &amp when I'm reading the individual elements in the other table.

2
  • 1
    Is this TSQL for SQL-Server? Please tag the question appropriately. It makes a difference, as different database engines have different string/XML handling capabilities. Commented May 9, 2014 at 4:52
  • Hi, yes this is SQL-Server Commented May 9, 2014 at 4:57

1 Answer 1

1

You can "XMLify" your string using for xml path.

Query:

declare @string_to_split nvarchar(max) = '&,<,>,'',"'
declare @delimiter nvarchar(100) = ','
declare @xml xml

set @xml = N'<t>' + replace((select @string_to_split for xml path('')), @delimiter, N'</t><t>') + N'</t>'

select @xml

Result:

<t>&amp;</t>
<t>&lt;</t>
<t>&gt;</t>
<t>'</t>
<t>"</t>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that. I'll give it a go. How do I then un'XMLify' the xml elements so I can store element one as a string in employee_first column in another table?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.