This topic provides XQuery examples against XML instances that are stored in various xml type columns in the AdventureWorks database. For an overview of each of these columns, see xml Data Type Representation in the AdventureWorks Database.
A. Retrieve local name of a specific node
The following query is specified against an untyped XML instance. The query expression, local-name(/ROOT[1]), retrieves the local name part of the specified node.
declare @x xml
set @x='<ROOT><a>111</a></ROOT>'
SELECT @x.query('local-name(/ROOT[1])')
-- result = ROOT
The following query is specified against the Instructions column, a typed xml column, of the ProductModel table. The expression, local-name(/AWMI:root[1]/AWMI:Location[1]), returns the local name, Location, of the specified node.
SELECT Instructions.query('
declare namespace AWMI="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions" ;
local-name(/AWMI:root[1]/AWMI:Location[1])') as Result
FROM Production.ProductModel
WHERE ProductModelID=7
-- result = Location
B. Using local-name without argument in a predicate
The following query is specified against the Instructions column, typed xml column, of the ProductModel table. The expression returns all the element children of the <root> element whose local name part of the QName is "Location". The local-name() function is specifed in the predicate and it has no arguments The context node is used by the function.
SELECT Instructions.query('
declare namespace AWMI="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions" ;
/AWMI:root//*[local-name() = "Location"]') as Result
FROM Production.ProductModel
WHERE ProductModelID=7
The query returns all the <Location> element children of the <root> element.