Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 6142 |  Welcome, Guest!   Register  Login
Home > Articles > Sql Server > Extracting values from XML nodes and present in comma separated values using XQuery in SQL Server

Extracting values from XML nodes and present in comma separated values using XQuery in SQL Server

Article posted by Niladri.Biswas on 6/10/2012 | Views: 2345 | Category: Sql Server | Level: Beginner | Points: 250 red flag


In this article we will look into some methods as how to extract values from XML nodes and present in comma separated values using XQuery

Download


 Download source code for Extracting values from XML nodes and present in comma separated values using XQuery in SQL Server


Introduction

In a recent requirement of mine, there has been a problem being stated as under

There are many employees into the system and they can have multiple emails.The emails are being stored into xml nodes as under

<EmployeeEmails> 
<Email>FirstEmail@employee.com</Email>
<Email>SecondEmail@employee.com</Email>
<Email>ThirdEmail@employee.com</Email>
</EmployeeEmails>

What we need to generate is a comma separated list as given below.

Emails
------
FirstEmail@employee.com,SecondEmail@employee.com,ThirdEmail@employee.com

Solution 1:Using Node function

Let us first try to extract the node values by using the .nodes() function as shown under

DECLARE @InputData XML = '<EmployeeEmails> 
<Email>FirstEmail@employee.com</Email>
<Email>SecondEmail@employee.com</Email>
<Email>ThirdEmail@employee.com</Email>
</EmployeeEmails>'

SELECT EmailColumn.value('.','varchar(100)') AS EmailData
FROM @InputData.nodes('/EmployeeEmails/Email') AS EmailTable(EmailColumn)

/*
EmailData
-------------------------
FirstEmail@employee.com
SecondEmail@employee.com
ThirdEmail@employee.com
*/

The .nodes() function creates an "inline" table of XML fragments for each "row" in the table that contains one <Email> node. We can then query on and extract the contents of the XML node.

Once we get the row-wise records,next we can apply FOR XML PATH to get the rows transformed into columns with comma seperated list as shown under

DECLARE @InputData XML ='<EmployeeEmails> 
<Email>FirstEmail@employee.com</Email>
<Email>SecondEmail@employee.com</Email>
<Email>ThirdEmail@employee.com</Email>
</EmployeeEmails>'
;WITH EmailCTE AS
(
SELECT EmailColumn.value('.','varchar(100)') AS EmailData
FROM @InputData.nodes('/EmployeeEmails/Email') AS EmailTable(EmailColumn)
)

SELECT ',' + CAST(EmailData AS VARCHAR(MAX))
FROM EmailCTE
FOR XML PATH('')

/*
XML_F52E2B61-18A1-11d1-B105-00805F49916B
-------------------------------------------------------------------------
,FirstEmail@employee.com,SecondEmail@employee.com,ThirdEmail@employee.com
*/

We can make out that the data is not formatted properly as there is a comma in the before any data.Just to give a final touch to the solution, we can employ Stuff function inorder to extract the extra comma at the beginning.The full query with desired output is as under

DECLARE @InputData XML = '<EmployeeEmails> 
<Email>FirstEmail@employee.com</Email>
<Email>SecondEmail@employee.com</Email>
<Email>ThirdEmail@employee.com</Email>
</EmployeeEmails>'
;WITH EmailCTE AS
(
SELECT EmailColumn.value('.','varchar(100)') AS EmailData
FROM @InputData.nodes('/EmployeeEmails/Email') AS EmailTable(EmailColumn)
)
SELECT Emails = STUFF(EmailList,1,1,'') from
(
SELECT ',' + CAST(EmailData AS VARCHAR(MAX))
FROM EmailCTE
FOR XML PATH('')
)X(EmailList)

/*
Emails
-------------------------------------------------------------------------
FirstEmail@employee.com,SecondEmail@employee.com,ThirdEmail@employee.com
*/

Solution 2:Using Query function

Let us first execute the below code

DECLARE @InputData XML = '<EmployeeEmails> 
<Email>FirstEmail@employee.com</Email>
<Email>SecondEmail@employee.com</Email>
<Email>ThirdEmail@employee.com</Email>
</EmployeeEmails>'

SELECT @InputData.query('data(EmployeeEmails/Email)') As Emails

/*
Emails
------------------------------------------------------------------------
FirstEmail@employee.com SecondEmail@employee.com ThirdEmail@employee.com

*/

The above query returns a space separated list with the values stored in the XML fragment.To fulfill our objective we can use Replace function to replace the spaces with comma's. But the query() method returns the data of XML type which will hinder to do so.Henceforth, first we need to convert the XML data type to varchar and then we can use the Replace function.

The below query will,however, convert the XML result to string result

DECLARE @InputData XML = '<EmployeeEmails> 
<Email>FirstEmail@employee.com</Email>
<Email>SecondEmail@employee.com</Email>
<Email>ThirdEmail@employee.com</Email>
</EmployeeEmails>'
SELECT @InputData.query('data(EmployeeEmails/Email)').value('.','varchar(100)') As Emails

Finally, we can use the replace function to accomplish the goal

DECLARE @InputData XML = '<EmployeeEmails> 
<Email>FirstEmail@employee.com</Email>
<Email>SecondEmail@employee.com</Email>
<Email>ThirdEmail@employee.com</Email>
</EmployeeEmails>'
SELECT REPLACE
(
@InputData.query('data(EmployeeEmails/Email)').value('.','varchar(100)')

,' ' -- replace the white spaces

,',' -- replace the white spaces with commas
) AS Emails

/*
Emails
-------------------------------------------------------------------------
FirstEmail@employee.com,SecondEmail@employee.com,ThirdEmail@employee.com

*/

Conclusion

So in this short article, we have seen as how to parse the XML nodes inorder to obtain the data by using Nodes() and Query() functions.Hope this will be helpful to others.Zipped file is attached.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:6 year(s)
Home page:http://www.dotnetfunda.com
Member since:Monday, October 25, 2010
Level:Diamond
Status: [Member]
Biography:Lead Engineer at HCL Technologies Ltd., having 6 years of experience in IT field.
I love to explore new technologies and love challenges and try to help others as much as possible not only by coding but also by all possible means.
>> Write Response - Respond to this post and get points
Related Posts

DBAs often need to track the changes being made to the database objects such as tables, user-defined functions and stored procedures etc.,. Our team size was 10 and a couple of members were responsible for each of the modules. My requirement was to track the changes made to the stored procedures right from its creation. My earlier articles explained on how source control can be made available for new/existing stored procedures. If you have missed those articles please catch them up at, http://dotnetfunda.com/articles.

To make SQL Queries Case Sensitive using Collation. You can make SQL Queries Case sensitive at the column level or Table level or DataBase level

This article will expalins you how to delete and update a Child Table records implicitly when updating or deleting a Parenet Table.

We all knows that the SQL provides the basic functionality, in terms of what can be searched for or filtered by. But some more advanced functions may be obtained, if the user knows a few tricks. Here are given few very basic tricks which can help to speed up the executions of your SQL scripts

This is part 29 of the series of article on SSIS. In this article, we are going to learn how to create local folder using FTP Task in SSIS Package.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/19/2013 2:33:26 PM