T-Sql xml query

How to 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?

+3
source share
2 answers

title is not an attribute. The following work.

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

There is no need to trim the XML in the FROM if you only need one value.

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

Source: https://habr.com/ru/post/906305/


All Articles