-- ============================================================
-- sample code that shows how to merge different nodes
-- in the same XML document by using FOR XML PATH()
-- Donabel Santos
-- ============================================================
-- sample XML snippet
DECLARE @sampleXML XML
SET @sampleXML =
'
<Contacts>
<Contact Type="Main" Value="John Doe">
<Locations>
<Location Type="Headquarters" Address="123 XYZ" City="New Westminster"
Province="BC" Country="CA" PostalCode="V1L1B6" />
</Locations>
<Phones>
<Phone Type="Main" Value="6041112222" />
<Phone Type="Secondary" Value="6041113333" />
<Phone Type="Fax" Value="6045553322" />
</Phones>
<Emails>
<Email Type="Main" Value="john.doe@email.ca" />
<Email Type="Secondary" Value="contact@email.ca" />
</Emails>
</Contact>
<Contact Type="Secondary" Value="Mary Smith">
<Locations>
<Location Type="Headquarters" Address="123 ABC" City="New Westminster"
Province="BC" Country="CA" PostalCode="V1L1B6" />
</Locations>
<Phones>
<Phone Type="Main" Value="6041112255" />
<Phone Type="Secondary" Value="6041113777" />
<Phone Type="Fax" Value="6045553311" />
</Phones>
<Emails>
<Email Type="Main" Value="mary.smith@email.ca" />
<Email Type="Secondary" Value="contact@email.ca" />
</Emails>
</Contact>
</Contacts>
'
-- get only the elements underneath <Phones> and <Emails>
SELECT
@sampleXML.query ('(/Contacts/Contact/Phones/*)'),
@sampleXML.query ('(/Contacts/Contact/Emails/*)')
FOR XML PATH('')
-- result
/*
<Phone Type="Main" Value="6041112222" />
<Phone Type="Secondary" Value="6041113333" />
<Phone Type="Fax" Value="6045553322" />
<Phone Type="Main" Value="6041112255" />
<Phone Type="Secondary" Value="6041113777" />
<Phone Type="Fax" Value="6045553311" />
<Email Type="Main" Value="john.doe@email.ca" />
<Email Type="Secondary" Value="contact@email.ca" />
<Email Type="Main" Value="mary.smith@email.ca" />
<Email Type="Secondary" Value="contact@email.ca" />
*/
Related posts:
- SQLXML : How to Work With XML Elements (or Nodes) in SQL Server ...
- Order of Attribute-Centric Columns in FOR XML PATH matters ...
- Valid SQLXML XSD Data Types, and Sample SQL Server XML Schemas ...
- SQLXML : How to Create an XML Schema ...
- SQLXML : How to Alter Existing Column Schema (XSD) ...
- SQLXML : How to Join Multiple XML Snippets (using query() and UNION ALL) ...
Filed under:
SQLXML











Leave a comment