April 27, 2011

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


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

 
  Feedback:

comments

0 Responses to "SQL Server: String operations in XML document‏"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions