klashagelqvist
klashagelqvist

Reputation: 1261

T-Sql xml query

How can i get the title in the following xml document

DECLARE @xVar XML
SET @xVar = 
  '<reportdata genre="security" publicationdate="2002" ISBN="0-7356-1588-2">
   <title>Writing Secure Code</title>
   <author>
      <first-name>Michael</first-name>
      <last-name>Howard</last-name>
   </author>
   <author>
      <first-name>David</first-name>
      <last-name>LeBlanc</last-name>
   </author>
   <price>39.99</price>
   </reportdata>'

SELECT [Title]= reportdata.item.value('@title', 'varchar(40)')

FROM   @xVar.nodes('/reportdata') AS reportdata(item)

This query always returns null , any ideas?

Upvotes: 3

Views: 4010

Answers (2)

Mikael Eriksson
Mikael Eriksson

Reputation: 139010

There is no need to shred the XML in the FROM clause if you only want one value.

SELECT [Title]= @xVar.value('(/reportdata/title)[1]', 'varchar(40)')

Upvotes: 2

Martin Smith
Martin Smith

Reputation: 454019

title is an element not an attribute. The following works.

SELECT [Title]= reportdata.item.value('.', 'varchar(40)')
FROM   @xVar.nodes('/reportdata/title[1]') AS reportdata(item)  

Upvotes: 3

Related Questions