In 2005 version of SQL Server, XQuerying was introduced. It’s a powerful feature and when used together with a CTE, it helps to keep code simple and clean. I use XML extensively in my code and many a time, I find myself looking up code, searching the internet or trying things out myself. I hope this post will be a single point of reference to most of the usual XQuery coding.
Following is a simple script to read from an XML variable. Same code can be used to read from an XML column as well.
NOTE: I will append more XQuery code samples to this post.
DECLARE @xmlProduct XML = '<Catalog> <Product> <Name>Selle Italia Road</Name> <Code>SIR-1</Code> <Category>Saddle</Category> <Description>Sleek saddle from Selle Italia</Description> <UnitPrice>50</UnitPrice> <Currency>USD</Currency> </Product> <Product> <Name>Brooks Tourer</Name> <Code>BT-T</Code> <Category>Saddle</Category> <Description>Brooks leather saddle for touring</Description> <UnitPrice>120</UnitPrice> <Currency>USD</Currency> </Product> </Catalog> ' --Read from nodes SELECT c.value('Name[1]','varchar(50)') [ProductName], c.value('Code[1]','varchar(50)') [Code], c.value('Category[1]','varchar(50)') [Category], c.value('UnitPrice[1]','varchar(50)') + CHAR(32) + c.value('Currency[1]','varchar(50)') [Price], c.value('Description[1]','varchar(50)') [Description] FROM @xmlProduct.nodes('//Catalog/Product') AS TAB(c)
Output: