SQL Server: String operations in XML document‏

SQL Server versions starting from 2005 and onwards supports storing and retrieving data as XML format. Using the XML datatype, you can do lot of things such as splitting string, string concatenation etc. In this post, we will see how we can use XML datatype to split strings

Consider the following example:

sql-xml-split

Declare @string Varchar(100),@delimiter CHAR(1)
Set @string = 'See if you can you split this'
set @delimiter = ' '
Declare @Xml Xml
Select @Xml = Cast('<d>' +
                    Replace(@string, @Delimiter,'</d><d>') + '</d>' As Xml )
SELECT T.split.value('.', 'nvarchar(max)') AS data
FROM @XML.nodes('/d') T (split)


In the above example the variable @Xml is of type xml. It concatenates the
original string by replacing a space with </d><d> so that each word will be surrounded
by <d> and </d>. The string is split by identifying the elements within <d> and </d>.
OUTPUT
sql-xml-split-output

No comments:

Post a Comment