Thursday 17 November 2011

Reading XML

DECLARE @productXML AS XML

SET @productXML =
'<product>
 <data>
  <BoothId>22</BoothId>
  <Title>Product1</Title>
  <BoothProductLogo>a.jpg</BoothProductLogo>
  <UserBoothReps>
   <UserBoothRepId>7</UserBoothRepId>
   <UserBoothRepId>8</UserBoothRepId>
   <UserBoothRepId>9</UserBoothRepId>
  </UserBoothReps>
 </data>
 <data>
  <BoothId>22</BoothId>
  <Title>Product2</Title>
  <BoothProductLogo>b.jpg</BoothProductLogo>
  <UserBoothReps>
   <UserBoothRepId>23</UserBoothRepId>
   <UserBoothRepId>30</UserBoothRepId>
  </UserBoothReps>
 </data>
</product>'

SELECT
    p.c.query('.'),
    p.c.value('BoothId[1]', 'BIGINT') AS BoothId,
    p.c.value('Title[1]', 'VARCHAR(500)') AS Title,
    p.c.value('BoothProductLogo[1]', 'VARCHAR(200)') AS BoothProductLogo,
    u.c.value('.', 'INT') AS UserBoothRepId
FROM @productXML.nodes('/product/data') p(c)
    CROSS APPLY p.c.nodes('UserBoothReps/UserBoothRepId') u(c)

No comments:

Post a Comment